尝试处理错误时未定义基本服务,Angular

Base service undefined when trying to handle an error, Angular

我有一个扩展基础服务以处理错误数据的服务。

例如

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.')
   }

我该如何纠正?

你有一个 this 引用问题,当你在 catch 函数中传递一个函数时,this 不再引用该对象,你要么使用箭头函数,要么在其中调用 handleError,

catch((err)=>this.handleError(err)) //it will save the context

或使用绑定方法

   catch(this.handleError.bind(this)) it will do the same