TypeError: Cannot read property 'sendNotification' of undefined in Angular 8

TypeError: Cannot read property 'sendNotification' of undefined in Angular 8

我有一个 AppRestService 服务,方法如下:

export class AppRestService implements OnDestroy {
  private readonly onDestroy = new Subject<void>();
  constructor(private http: HttpClient, private sessSvc: SessionActivityService) { }
  ngOnDestroy() {
    this.onDestroy.next();
  }
  getData(route: string): Observable<any> {
    this.sessSvc.sendNotification("TEST works", 15);
    return this.http.get<any>(route).pipe(
      takeUntil(this.onDestroy),
      catchError(this.errorHandler),
    );
  }
  errorHandler(err: HttpErrorResponse) {
    let restErr: IErrorObjHttp = new ErrorObjHttp();
    restErr.errObj = err;
    if (err.error instanceof ErrorEvent) {
      restErr.type = "client";
      restErr.message = `An error occurred: ${err.error.message}.`;    // Client-side error
    } else {
      restErr.type = "server";
      restErr.message = `Server returned code : ${err.status}, error message is ${err.message}.`;    // Service-side error
    }
   
    console.log("Error:", restErr);
    this.sessSvc.sendNotification(restErr.message, 15);
    console.log("post-sendNotification():", restErr.message);
    return throwError(restErr);
  }
}

我从不同的组件调用这个服务。问题是“this.sessSvc”(这是在此服务中调用以发送通知的另一个服务)在 errorHandler() 方法中未定义并且给出错误。从 getData() 方法调用 errorHandler() 方法。

TypeError: Cannot read property 'sendNotification' of undefined

但是当在 getData() 方法中直接调用“this.sessSvc”并且能够 sendNotification 时它工作正常。我错过了什么?

这是我从不同组件调用服务的方式

export class PlanComponent implements OnInit {
  planList: any;
  constructor(private service: AppRestService) { }
  ngOnInit() {
    this.planList = this.service.getData("/api/plans/hhjkhhk");
  }
}
catchError(this.errorHandler)

这可以是:

catchError(this.errorHandler.bind(this))

或:

catchError(error => this.errorHandler(error)) // as Gunnar pointed

这是因为 errorHandler 中的 this 上下文成为函数本身而不是 AppRestService

但是 Arrow functions 不绑定自己的 this,而是从父作用域继承 this。

此外,bind() 方法创建了一个新函数,在调用时将其 this 关键字设置为提供的值,并在调用新函数时在任何提供的参数之前使用给定的参数序列。

部分参考资料:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_objects/Function/bind

https://www.codementor.io/@dariogarciamoya/understanding-this-in-javascript-with-arrow-functions-gcpjwfyuc