【问题标题】:Base service undefined when trying to handle an error, Angular尝试处理错误时未定义基本服务,Angular
【发布时间】: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


【解决方案1】:

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

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

或者使用绑定方法

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-02-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多