I have one Service that returns a single Observable. Now I'm looking for the right / most efficient way to get some results from this Observable without writing too much code.
MyService returns Observable<Array<Foo>>
MyComponentcalls myService.getFoos()and should output the first 5 elements from the array, as well as the total length of the array and the number of elements that are not shown.
Here is 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 great, but I use the handset async4 times. Which (as far as I know) will result in 4 Signatures. It is not necessary at all, I think (?)
Of course, I could manually sign up for constructorfrom MyComponent, and then live without pipes async. But then I have to take care to unsubscribe.
?