【问题标题】:Return value in Catch Angular HttpClient在 Catch Angular HttpClient 中返回值
【发布时间】:2017-09-19 05:11:03
【问题描述】:

我正在尝试创建一个通用服务来从服务器获取一些设置。当发生错误时,我想捕获此错误并返回一个默认值(本地我有一个默认配置,应该在发生错误时使用)。

由于我使用的是Angular 4.3.6,所以我可以使用新的HttpClientModule

代码:

/**
  * Fetches the map settings
  * @returns { Observable<MapConfiguration> }
  */

public getMapConfiguration(): Observable<MapConfiguration> {
  return this.http.get<MapConfiguration>(MapService.MAPSETTINGSURL)
    .catch((exception) => {
      console.warn('Could not fetch map configuration due to: ', exception);
      return new MapConfiguration();
    });
} 

此代码给出以下错误:

Type 'MapConfiguration' is not assignable to type 'ObservableInput&lt;{}&gt;'.

我是 Observables 的新手(习惯于 Promise),有了 Promise,我可以在 catch 中返回一个值。我该如何解决这个问题,以便始终返回一个值?

我想让服务处理错误,而不是 subscriber

【问题讨论】:

    标签: angular typescript observable


    【解决方案1】:

    为了始终有一个返回值,您可以在 catch 中使用 return Observable.of(new MapConfiguration()); 将其包装为可观察的。

    【讨论】:

      【解决方案2】:
      return Observable.of(new MapConfiguration());
      

      将您的对象作为消息生成错误

      return Observable.throw(new MapConfiguration());
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2012-05-20
        • 2020-10-25
        • 1970-01-01
        • 2012-04-24
        • 2018-10-31
        • 1970-01-01
        • 2023-03-30
        相关资源
        最近更新 更多