簡體   English   中英

http 服務的 OnPush Changedetection

[英]OnPush Changedetection for a http service

我想調用一個 http api 並使用 ChangeDetectionStrategy.OnPush 加載數據。 我知道如何通過調用 detectchanges() 使用 ChangeDetectorRef 來解決這個問題。 調用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();
    });
}

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', {}))
      );
  }

現在這工作得很好。 但我的問題是是否有更好的方法來做到這一點? 我一直聽說我們不應該真正使用 changedetectionref markforCheck() 或 detectChanges() ,因為它是手動調用的。 我不想使用異步管道,因為如果 http 響應失敗,我無法捕獲錯誤。

這正是它應該做的方式。

通過使用ChangeDetectionStrategy.OnPush ,您基本上會說,為了獲得更好的性能,您可以接受 Angular 不為您檢測所有更改,並且您將在需要時手動觸發更改檢測。 這里需要它,您手動觸發它。 完全符合預期。

暫無
暫無

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

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