简体   繁体   中英

Angular2 + async pipe: Get multiple values from a single Observale

I have a single Service, which returns a single Observable. Now I'm looking for the correct / most efficient way to get multiple results from this Observable without writing too much code.

  • MyService returns an Observable<Array<Foo>>

  • MyComponent calls myService.getFoos() and should output the first 5 elements from the array, and the total length of the array, and the number of elements not shown.

Here's my current code:

@Injectable()
export class MyService {
  foos = new BehaviorSubject<Array<Foo>>([]);

  getFoos() {
    return this.foos.asObservable();
  }
}



@Component({
  template: `
    Total: {{ totalCount | async }}
    Omitted: {{ (totalCount | async) - (maxFiveItems | async).length }}
    <div *ngFor="let item of maxFiveItems | async">
      {{item.bar}}
    </div>
  `
})
export class MyComponent {
  totalCount: Observable<number>;
  maxFiveItems: Observable<Array<Foo>>;

  constructor(myService:MyService) {
    this.totalCount = myService.getFoos()
        .map(arr => arr.length);

    this.maxFiveItems = myService.getFoos()
        .map(arr => arr.slice(0, 5));
  }
}

The result looks fine, but I'm using the async pipe 4 times. Which (as far as I know) will result in 4 Subscriptions. This shouldn't be necessary at all I guess (?)


Of course I could manually subscribe within the constructor of MyComponent and then live without async pipes. But then I have to take care of unsubscribing myself.

Is there any other way to handle this?

There's nothing wrong with what you're doing assuming that myService.getFoos() somewhere inside uses share() operator so all your async pipes share the same subscription to the source. If you're using BehaviorSubject as in this example then you're fine.

What you mentioned about subscribing yourself in the constructor is what came to my mind immediately. I don't see manual unsubscription as a problem though.

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