我试图在每个以Angular 2结尾的请求中添加一个加载微调器,所以我扩展了Http服务,调用它为HttpService.在每次请求之后,我想在捕获错误后调用finally()函数,以便我可以停止加载微调器.
但打字稿说:
[ts] Property ‘finally’ does not exist on type ‘Observable’.
import { AuthService } from './../../auth/auth.service'; import { Injectable } from '@angular/core'; import { Http,XHRBackend,RequestOptions,RequestOptionsArgs,Request,Response,Headers } from '@angular/http'; import { Observable } from 'rxjs/Observable'; import 'rxjs/add/operator/catch'; import 'rxjs/add/observable/throw'; @Injectable() export class HttpService extends Http { constructor( backend: XHRBackend,options: RequestOptions,private authservice: AuthService ) { super(backend,options); this.updateHeaders(options.headers); } request(url: string|Request,options?: RequestOptionsArgs): Observable<Response> { return super.request(url,options) .catch((response: Response) => this.authError(response)) .finally(() => { // ... /* Do something here when request is done. For example finish a spinning loader. */ }); } private authError(response: Response) { if (response.status === 401 || response.status === 403) { this.authservice.logout(); } return Observable.throw(response); } private updateHeaders(headers: Headers) { headers.set('Content-Type','application/json'); if (this.authservice.isloggedIn()) { headers.set('Authorization',`Bearer ${this.authservice.getToken()}`); } } }
如何在每个http请求之后运行一些代码?这样做的最佳方式是什么?
你忘了导入它:
import 'rxjs/add/operator/finally';