Tom*_*m H 0 observable rxjs typescript angular
我目前正在通过使用HTTPClient学习Angular 6和RXJS。
文档https://angular.io/guide/http指出,可以将内捕获错误this.http.get
的使用方法pipe
,然后tap
像下面从官方文档举起例子。
getTextFile(filename: string) {
// The Observable returned by get() is of type Observable<string>
// because a text response was specified.
// There's no need to pass a <string> type parameter to get().
return this.http.get(filename, {responseType: 'text'})
.pipe(
tap( // Log the result or error
data => this.log(filename, data),
error => this.logError(filename, error)
)
);
}
Run Code Online (Sandbox Code Playgroud)
我试图像这样在我的方法中复制它
getLeads() : Observable<Lead[]> {
return this.http.get<Lead[]>('http://localhost:3000/leads').pipe(
tap (
error => console.log('error')
)
);
}
Run Code Online (Sandbox Code Playgroud)
但是它并没有捕获错误tap()
,但是当catchError
像下面这样使用时,它确实可以工作。
getLeads() : Observable<Lead[]> {
return this.http.get<Lead[]>('http://localhost:3000/leads').pipe(
catchError(this.errorHandlerService.handleError('Could not get Leads', [])),
);
}
Run Code Online (Sandbox Code Playgroud)
有以下原因导致无法正常工作吗?
tap (
error => console.log('error')
)
Run Code Online (Sandbox Code Playgroud)
这些方法的回调名称无关紧要。
tap (
error => console.log('error')
)
Run Code Online (Sandbox Code Playgroud)
在这种情况下,“错误”实际上是“成功”回调。如果要处理错误,则需要tap操作符的第二个参数。
tap (
success => console.log('success'),
error => console.log('error')
)
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
4144 次 |
最近记录: |