【问题标题】:How to handle an API response that might be an empty object with rxjs Observables?如何使用 rxjs Observables 处理可能是空对象的 API 响应?
【发布时间】:2020-05-22 10:41:03
【问题描述】:

我可以同时编辑前端和后端

我有一个获取公报的服务。该公报可能存在(有一个公报处于活动状态)也可能不存在(没有公报处于活动状态),因此 API 可能会使用公报的 JSON 对象或空 JSON 对象进行响应。

我是这样处理的:

getCommunique(): Observable<Communique | {}> {
  return this.http.get(this.apiUrl + '/getCommunique').map((response) => {
    if (Object.keys(response.json()).length != 0) {
      return new Communique(response.json())
    } else {
      return {}
    }
  });
}

这是我的Communique 班级:

export class Comunique {
  public id: number;
  public title: string;
  public content: string;
  public date: Date;
  public url: string;
  public imageUrl: string;

  constructor(input: ComuniqueRaw) {
    this.id = input.id;
    this.title = input.title;
    this.content = input.content;
    this.date = new Date(input.date.timestamp * 1000);
    this.url = 'url' + input.slug;
    this.imageUrl = 'url' + input.image;
  }
}

这行得通...但这似乎是一种解决方法。 observable 不应该只返回Communique 对象吗?但是如果没有有效的公报,Communique 对象将如何创建?我的意思是,我可以在Communique 类中添加一个类似于public exists: boolean; 的字段,但这似乎也是一种解决方法(一个只包含一个boolean 的对象)。

我是否以正确的方式处理它?或者...如何使用 rxjs Observables 处理可能是空对象的 API 响应?

【问题讨论】:

    标签: angular api ionic-framework rxjs ionic3


    【解决方案1】:

    http.get() observable 总是返回一次且只返回一次。如果服务器响应一个空对象,那么忽略它不是 http 客户端的责任 - 这是一个有效的 http 响应。

    如果没有公报对象,我会说你的服务器应该返回 404,然后你用 rxjs catchError 捕获它,它会单独处理这种情况。

    编辑:

    如果您希望始终返回带有空响应或对象的 200,那么您实现的模式似乎很好。

    编辑2:

    我刚刚注意到您使用的是旧的 .map() 方法。我的 catchError() 答案是使用相对较新的管道运算符。

    getCommunique(): Observable<Communique> {
      return this.http.get(this.apiUrl + '/getCommunique').pipe(
        map(response => new Communique(response.json())),
        catchError(() => of(null))
      );
    }
    

    【讨论】:

    • 地图中的错字。如果您使用的是 Angular 7+,那么它应该是 mapTo()
    • 没有。 mapTo 忽略输入。在这种情况下,我们希望将输入响应映射到新的 Communique 对象。
    猜你喜欢
    • 2017-05-18
    • 2019-04-15
    • 2021-02-18
    • 2014-02-28
    • 2019-10-28
    • 1970-01-01
    • 2013-09-29
    • 2017-03-27
    • 1970-01-01
    相关资源
    最近更新 更多