在嵌套和从属订阅中手动触发错误功能

时间:2018-04-16 07:43:48

标签: angular rxjs observable

在我正在处理的Angular 5应用程序上,我必须手动触发可观察的错误。我已经查看了类似的问题here,但没有结果。 Observable函数有两个嵌套的observable(示例中为getSubscription)。

以下是Plunker (link)的一个小例子 我的代码在app.component.ts内。 triggerErrorgetSubscription是关键要素。重要的部分是两个嵌套和依赖订阅。为简单起见,我对两个订阅使用相同的调用,这些应该是两个嵌套订阅的占位符,在真实的应用程序中,这将是两个不同的订阅

无论是抛出错误还是发送成功响应,订阅始终会跳转到具有成功结果的方法。如果发生错误,订阅如何跳转到相应的方法?

具有两个嵌套和相互依赖订阅的结构非常重要,在提出解决方案时必须予以考虑!

2 个答案:

答案 0 :(得分:1)

我认为您的getSubscription功能不正确。你可以简单地将其更改为:

getSubscription(): Observable<boolean> {
        return this.earthquakeService.getRecentEarthquakes().map((recent) => {
            if(false) {
                return true;
            } else {
                console.log('error thrown');
                throw Observable.throw('ERROR');
            }
        });
    }

当你使用map on和observable时,最后你会返回另一个observable。然后你可以得到结果。无需再次在地图内订阅

<强>更新

如果你想使用两个不同的observable,你可以通过将它们链接在一起来工作:

getSubscription(): Observable<boolean> {
        return this.earthquakeService.getRecentEarthquakes().map((recent) => {
            // doing something with "recent" 
        }).switchMap((recent)=>{
          // you can use some condition here to either use the inner observable,
          // or return some other observable. just remember that you should return 
          // `Observable` here. this is the inner observable:
              return this.earthquakeService.getRecentEarthquakes()
            }).map((next) => {
                    if(false) {
                    return true;
                } else {
                    console.log('error thrown');
                    throw Observable.throw('ERROR');
                }
                });
        }

答案 1 :(得分:0)

如果您使用的是角度5,那么最好使用HttpClient而不是Http。然后你可以使用管道作为你的http方法,并在其中写入catchError函数。

Read this article

注意1.如果您的客户端源(localhost:4200)与服务器源不同,则必须使用angular proxy从服务器接收适当的错误。

阅读How to set proxy on an angular Cli project

最后,为了定制和翻译你的错误,你可以将功能用于你的服务,如下所示。

private handleError(error: HttpErrorResponse) {
  if (error.error instanceof ErrorEvent) {
    // A client-side or network error occurred. Handle it accordingly.
    console.error('An error occurred:', error.error.message);
  } else {
    // The backend returned an unsuccessful response code.
    // The response body may contain clues as to what went wrong,
    console.error(
      `Backend returned code ${error.status}, ` +
      `body was: ${error.error}`);
  }
  // return an ErrorObservable with a user-facing error message
  return new ErrorObservable(
    'Something bad happened; please try again later.');
}; 

将从HttpClient管道调用。如下所示

getConfig() {
  return this.http.get<Config>(this.configUrl)
    .pipe(
      catchError(this.handleError)
    );
}

希望有所帮助。

相关问题