【发布时间】:2019-11-13 04:24:59
【问题描述】:
我在服务中有一个项目列表,以及一个将该列表包装在 observable 中的 getter。
observable 在带有async 管道的组件视图中使用,并按预期工作。当列表更新时,视图也会更新。
我还有一个不同的组件需要根据 id 从该列表中获取特定项目的 observable。
问题是具有该 id 的项目在被请求时可能尚未在列表中。
我怎样才能实现这一目标?
我尝试过的一些示例:
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);
}
}
【问题讨论】:
-
我们是否需要在 Angular 服务中有一个
subscribe()代码块?
标签: angular rxjs observable