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 anObservable<Array<Foo>>
MyComponent
callsmyService.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?