【发布时间】:2020-06-17 14:42:13
【问题描述】:
我有一个服务扩展了基础服务来处理错误数据。
例如
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错误时重定向用户,则基础服务中的引用为空。
见下文,得到错误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.')
}
我该如何解决这个问题?
【问题讨论】:
-
角 cli 是 4.3.5
标签: angular observable angular2-services