在嵌套订阅和依赖订阅中手动触发错误功能



在我正在开发的 Angular 5 应用程序上,我必须手动触发可观察量的错误。我已经在这里看过一个类似的问题,但没有结果。具有可观察量的函数有两个嵌套的可观察量(示例中getSubscription)。

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

无论是引发错误还是发送成功的响应,订阅始终跳转到具有成功结果的方法。如果出现错误,订阅怎么可能跳转到相应的方法?

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

如果你使用的是 angular 5 ,那么你最好使用 HttpClient 而不是 Http。然后你可以将管道用于你的http方法,并在其中编写catchError函数。

阅读这篇文章

注意 1. 如果您的客户端来源(即 localhost:4200 )与您的服务器来源不同,那么您必须使用 Angular 代理从服务器接收适当的错误。

阅读如何在角度 CLI 项目上设置代理

最后,要自定义和翻译您的错误,您可以使用一个函数到您的服务中,如下所示。

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)
);
}

希望对您有所帮助。

我认为您的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 时,最后您将返回另一个可观察量。 稍后您可以订阅结果。 无需再次在地图内订阅

更新:

如果要使用两个不同的可观察量,可以通过将它们链接在一起来工作,如下所示:

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');
}
});
}

最新更新