【问题标题】:TypeError: Cannot read property 'sendNotification' of undefined in Angular 8TypeError:无法读取 Angular 8 中未定义的属性“sendNotification”
【发布时间】:2020-08-19 20:03:12
【问题描述】:

我有一个具有以下方法的服务 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

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

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

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

【问题讨论】:

  • 两点,你们在哪里提供服务?在根?另外,在您的PlanComponent 中,您是否在某个时候在planList 上使用了异步管道?如果没有订阅,getData 将永远不会真正执行。
  • 我还没试过你是怎么做的,但我想catchError这样:catchError(error =&gt; this.errorHandler(error))
  • 只是好奇,如果你使用这种风格的函数声明,它会起作用吗? errorHandler=(err: HttpErrorResponse)=&gt; { ... } }
  • @GunnarB.&lt;ng-container *ngFor="let plan of (planList | async)"&gt; 是在 PlanComponent 的 html 上使用异步管道
  • @DJBurb 是的,除非针对此特定问题,否则它工作正常

标签: javascript angular angular8


【解决方案1】:
catchError(this.errorHandler)

这可以是:

catchError(this.errorHandler.bind(this))

或者:

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

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

但是Arrow functions 并没有绑定自己的 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

【讨论】:

    猜你喜欢
    • 2020-02-22
    • 1970-01-01
    • 2019-12-07
    • 2014-11-29
    • 2018-10-29
    • 2021-07-21
    • 2018-05-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多