簡體   English   中英

類型錯誤:無法讀取 Angular 8 中未定義的屬性“sendNotification”

[英]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() 方法中直接調用“ 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

this是因為errorHandler中的上下文成為 function 本身而不是AppRestService

但是Arrow functions不綁定自己的 this,而是從父 scope 繼承 this。

此外, bind()方法創建一個新的 function,在調用時將其 this 關鍵字設置為提供的值,在調用新的 function 時,給定序列 arguments 位於任何提供的序列之前。

一些參考:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM