我有一项服务,该服务扩展了用于处理错误数据的基本服务。
例如
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错误时尝试使用基本服务中的实例重定向用户时,则基本服务中的引用为null。
请参见下文,获取错误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) {
//cannot read the property 'navigate' of undefined
this._router.navigate(["/login", false]);
}
return Observable.throw(message || 'We apologise. There was a technical error processing the request. Please try again later.')
}
我该如何纠正?
答案 0 :(得分:1)
您有一个此参考问题,当您在catch函数中传递一个函数时,此不再引用该对象,您必须使用箭头函数,并在其中调用handleError,
catch((err)=>this.handleError(err)) //it will save the context
或使用绑定方法
catch(this.handleError.bind(this)) it will do the same