这是带有 RXJS 6 的 angular 6 的答案。在您的请求函数中,它看起来与此类似。请注意,现在catch
已替换为catchError
和。同样在 RXJS 6 中,我们使用管道将我们希望执行的功能序列连接在一起,而不是之前的点链接。Observable.throw
throwError
//In your service
getData(url: string): Observable<any> {
let options = this.getHTTPOptions();
return this.http.get<any>(url, options).pipe(
catchError( (err: any, caught: Observable<any>) => { return
throwError(this.generalErrorHandler(err, caught)) } ) );
}
然后你可以有一个错误处理程序。return
关键是在上面的函数中指定关键字catchError
并在处理程序中返回错误。箭头 ( =>
) 允许您将调用函数的上下文传递给错误处理程序,这意味着您可以做一些很酷的事情,例如this.router.navigate(['someroute']);
(如果您的服务中导入了路由器)
//In your service
generalErrorHandler(error: any, caught: Observable<any>): Observable<any> {
console.log('error caught: ', error);
if( error.error.status == "INVALID_TOKEN" || error.error.status == "MAX_TOKEN_ISSUE_REACHED"){
console.log('token has expired');
this.logout();
return error;
}
return error;
}
一些关键的进口让这个工作:
//Imports for the service
import { HttpClient, HttpHeaders, HttpErrorResponse } from '@angular/common/http';
import { Http, Response } from '@angular/http';
import { catchError, map } from 'rxjs/operators';
import { Observable, throwError, of} from 'rxjs';
最后订阅请求以获取您的数据:
//In your component, don't forget to import your service
let response$ = this.someService.getData('url here');
response$.subscribe(
data => { console.log('do stuff to data here', data); },
err => { console.log("couldn't get data, maybe show error to user"); },
() => { console.log('function that is called upon finish'); }
);