简体   繁体   中英

OnPush Changedetection for a http service

I want to call a http api and load the data using ChangeDetectionStrategy.OnPush. I know how to go about it using the ChangeDetectorRef by calling detectchanges(). The main component calling the Service is:

  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:

  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. I do not want to use async pipe since i can't trap errors in case the http response fails.

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. Here it is needed, and you trigger it manually. Exactly as intended.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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