简体   繁体   English

http 服务的 OnPush Changedetection

[英]OnPush Changedetection for a http service

I want to call a http api and load the data using ChangeDetectionStrategy.OnPush.我想调用一个 http api 并使用 ChangeDetectionStrategy.OnPush 加载数据。 I know how to go about it using the ChangeDetectorRef by calling detectchanges().我知道如何通过调用 detectchanges() 使用 ChangeDetectorRef 来解决这个问题。 The main component calling the Service is:调用Service的主要组件是:

  ngOnInit() {
    this.invigilateService.getPhoto(this.email).subscribe((photo) => {
      this.photo = photo;
      if (this.photo.photo) {
        this.image = this.sanitizer.bypassSecurityTrustUrl(this.photo.photo);
      }
      this.imageLoaded = true;
      this.cdr.detectChanges();
    });
}

The invigilateService.ts is calling the http service: invigilateService.ts 正在调用 http 服务:

  getPhoto(email: string): Observable<Photo> {
    return this.http.get<Photo>(this.uri.getPhotoUri().replace('{email}',email))
      .pipe(
        tap(_ => console.log('fetched photo')),
        catchError(this.handleError<Photo>('getPhoto', {}))
      );
  }

Now this works just fine.现在这工作得很好。 But my question is if there is a better way to do this?但我的问题是是否有更好的方法来做到这一点? I keep hearing that we shouldn't really use changedetectionref markforCheck() or detectChanges() since its being manually called.我一直听说我们不应该真正使用 changedetectionref markforCheck() 或 detectChanges() ,因为它是手动调用的。 I do not want to use async pipe since i can't trap errors in case the http response fails.我不想使用异步管道,因为如果 http 响应失败,我无法捕获错误。

This is exactly the way it should be done.这正是它应该做的方式。

By using ChangeDetectionStrategy.OnPush , you basically say that, for the sake of better performance, you are fine with Angular not detecting all changes for you and that you will trigger change detections manually if needed.通过使用ChangeDetectionStrategy.OnPush ,您基本上会说,为了获得更好的性能,您可以接受 Angular 不为您检测所有更改,并且您将在需要时手动触发更改检测。 Here it is needed, and you trigger it manually.这里需要它,您手动触发它。 Exactly as intended.完全符合预期。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM