Benefits of async pipe with angular http request

2020-07-18 10:39发布

问题:

A lot of angular tutorial has suggest to use async pipe for auto unsubsribing observable.

What they claim:
async pipe is used for auto unsubscribing observer, or else you need to unsubscribe manually

What they did:
They use angular http to call REST api as an example for async pipe.

However, from my understanding, angular HTTP auto unsubscribe the observable. So, async pipe actually did not serve the intended purpose here as the observable will auto unsubscribe even without async pipe.

Is there any other reason why need to use async pipe here in this use case?

Sample implementation:

getUserList() {
    return this.http.get(apiUrl);
}

this.getUserList().subscribe(user => {
    this.userList = user;
});

<div *ngFor="let user of userlist | async">
    {{ user?.name }}
    {{ user?.email }}
</div>

回答1:

async pipe is used for auto unsubscribing observer, or else you need to unsubscribe manually

what they probably mean is that if you assign an observable to a class property:

import { interval } from 'rxjs/observable/interval';
let original = interval(1000);

class Comp {
  o = original;

and then later update that property with another observable

constructor() {
   setTimeout(() => {
      this.o = interval(500);
   }, 5000);
}

the subscription to the original observable will be disposed - async pipe will effectively call original.unsubscribe(). This can be seen in the sources:

@Pipe({name: 'async', pure: false})
export class AsyncPipe implements OnDestroy, PipeTransform {
  ...

  transform(obj: Observable<any>|Promise<any>|null|undefined): any {
    ....

    if (obj !== this._obj) {
      this._dispose();   <-------------------------
      return this.transform(obj as any);
    }

So, async pipe actually did not serve the intended purpose here as the observable will auto unsubscribe even without async pipe.

Is there any other reason why need to use async pipe here in this use case?

Yes, they used it for a different purpose - to save themselves some coding required in the approach you showed:

getUserList() {
    return this.http.get(apiUrl);
}

// this part can be eliminated if you use ` let user of getUserList() | async`
this.getUserList().subscribe(user => {
    this.userList = user;
});

<div *ngFor="let user of userlist">   <---- no need to use `async` here since `userlist` contains values, not observable
    {{ user?.name }}
    {{ user?.email }}
</div>


回答2:

You only need the async pipe if you use the observable directly in your template. So the main point of the async pipe is to use an observable in a template and the auto unsubscribing comes as additional benefit.

So either

<div *ngFor="let user of userlist">
</div> 

or

<div *ngFor="let user of getUserList() | async">
</div>