[英]Issue: How can I chain a function after an async Observable?
我有一个Angular组件,它允许选择列表中的项目。 因此, onInit()
应该执行以下操作:
实现此所需行为的承诺方式为:
ngOnInit() {
// 1) Load list of items (async)
this.loadItems()
// 2) after async load, set default selected item
.then(this.setDefaultSelectedItem);
}
// Calls the Service and sets `this.items` when the requested list
loadItems() {
return this.itemsService.getAll()
.then((items) => this.items = items);
}
this.setDefaultSelectedItem() {
// first item on the list of items by default
this.selectedItem = this.items[0];
}
我正在尝试使用rxjs
和Observables
实现相同的rxjs
。 到目前为止,我已经执行了以下操作:
ngOnInit() {
// 1) load list of pharmacies
this.loadItems();
// 2) select as default the first one (TODO)
}
loadItems() {
return this.itemsService.getAll()
.subscribe(items => this.items = items);
}
this.setDefaultSelectedItem() {
// first item on the list of items by default
this.selectedItem = this.items[0];
}
我最近一直在做一些研究,阅读了有关flatMap()
,但是在loadItems()
之后却无法链接setDefaultSelectedItem()
loadItems()
,因此我陷入了困境。
我想避免的含量this.setDefaultSelectedItem()
内.subscribe()
这样的块:
loadItems() {
return this.itemsService.getAll()
.subscribe(items => {
this.items = items;
this.selectedItem = this.items[0];
});
}
使用subscribe()
方法中的{}
,您可以实现一件以上的事情!
loadItems() {
return this.pharmaciesService.getAll()
.subscribe(items => {
this.items = items;
this.setDefaultSelectedItem();
});
}
编辑:
ngOnInit() {
// 1) load list of pharmacies
this.loadItems().subscribe(() => {
// 2) select as default the first one (TODO)
this.setDefaultSelectedItem()
});
}
loadItems() {
let obs = this.itemsService.getAll();
obs.subscribe(items => this.items = items);
return obs;
}
this.setDefaultSelectedItem() {
// first item on the list of items by default
this.selectedItem = this.items[0];
}
解决方案1-
loadPharmacies() {
return this.pharmaciesService.getAll()
.subscribe(
items => this.items = items;
this.setDefaultSelectedItem();
);
}
解决方案2-
loadPharmacies() {
return this.pharmaciesService.getAll()
.subscribe({
error: err => console.log(`Oops... ${err}`),
complete: () => console.log(`Complete!`),
});
}
然后,您可以采用完整的方法来做您想做的任何事情。
如果您有任何疑问,请告诉我。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.