I have an item list in a service, and a getter that wraps that list in an observable.
The observable is consumed in a components view with async pipe, and works as expected. When the list is updated, the view is updated.
I also have a different component that needs to get an observable of a specific item from that list, based on an id.
The thing is that the item with that id might not be in the list yet, when it is requested.
How can I go about achieving this?
Some examples of what I tried:
export class ItemsService {
private itemList: Item[] = [];
constructor() {
// get the list from the backend
}
// This is fine
getItemList(): Observable<Item[]> {
return of(this.itemList);
}
// This I assume does not work, because the pipe just applies map
//on whatever is now in the observable list
getItem(id: string): Observable<Item> {
return this.getItemList().pipe(map(items => items.find(item => item.id === id)));
}
// This I assume does not work as the local item is not yet set when I wrap it in an observable
//to return it, and when it eventually gets set by the callback, it's already out of scope.
// The weird thing to me is that the callback is only called at the beginning, when the list is empty,
//and not anymore when the list gets populated
getItem(id: string): Observable<Item> {
let item: Item;
this.getItemList().subscribe(items => {
console.log('callback called');
item = items.find(item => item.id === id);
});
return of(item);
}
}
subscribe()code block in an Angular service?