我有一个扩展基本服务以处理错误数据的服务。
例如
import { CurrentUserService } from './current-user.service';
import { CONFIG } from './../shared/base-urls';
import { BaseServiceService } from './base-service.service';
import { Injectable } from '@angular/core';
import { Http, Headers, Response, RequestOptions, ResponseContentType } from '@angular/http';
import { Router } from '@angular/router';
let baseUrl = CONFIG.baseUrls.url;
@Injectable()
export class ChildService extends BaseServiceService {
constructor(public _http: Http, public _currentUser: CurrentUserService, public _router: Router) {
super(_router, _http, _currentUser);
}
getFaqData() {
var headers = new Headers();
this.token = this._currentUser.getProfile().token;
let sessionId = this._currentUser.getProfile().sessionId;
headers.append('Authorization', `Bearer ${this.token}`);
headers.append('Content-Type', 'application/json; charset=utf-8');
return this._http.get(baseUrl + "api/UserAdmin/GetFaq",
{ headers: headers })
.map((response: Response) => response.json())
.catch(this.handleError)
}
}
[当位于基本服务中时发生错误this.handleError
,但是当尝试在401错误this
中使用实例(this._router.navigate
)来重定向用户时,则调用基本服务为空。
请参见下文,获取错误cannot read the property 'navigate' of undefined
//Inside BaseServiceService
constructor(public _router: Router, public _http: Http, public _currentUser: CurrentUserService) {
}
protected handleError(response: Response):any {
var message = "";
if (response.status == 401) {
this._router.navigate(["/login", false]);//cannot read the property 'navigate' of undefined
}
return Observable.throw(message || 'We apologise. There was a technical error processing the
request. Please try again later.')
}
我该如何纠正?
您有一个this参考问题,当您在catch函数中传递一个函数时,this不再引用该对象,您必须使用箭头函数,并在其中调用handleError ,
catch((err)=>this.handleError(err)) //it will save the context
或使用绑定方法
catch(this.handleError.bind(this)) it will do the same