TypeError:无法读取Angular 8中未定义的属性“ sendNotification”

时间:2020-08-19 20:03:12

标签: javascript angular angular8

我有一个使用以下方法的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);
  }
}

我从不同的组件调用此服务。问题是在errorHandler()方法中未定义“ this.sessSvc”(在该服务中被称为发送通知的另一个服务),并给出了错误。从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");
  }
}

1 个答案:

答案 0 :(得分:3)

catchError(this.errorHandler)

这可以是:

catchError(this.errorHandler.bind(this))

或者:

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

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

但是Arrow functions不会绑定自己的这个,而是从父范围继承一个。

此外,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