[基本服务,尝试处理错误时未定义,角度

问题描述 投票:0回答:1

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

例如

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

我该如何纠正?

angular observable angular2-services
1个回答
0
投票

您有一个this参考问题,当您在catch函数中传递一个函数时,this不再引用该对象,您必须使用箭头函数,并在其中调用handleError ,

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

或使用绑定方法

   catch(this.handleError.bind(this)) it will do the same
© www.soinside.com 2019 - 2024. All rights reserved.