Javascript 问题:如何在异步可观察事件之后链接函数?
我有一个角度组件,可以在列表中选择项目。因此,Javascript 问题:如何在异步可观察事件之后链接函数?,javascript,angular,promise,rxjs,observable,Javascript,Angular,Promise,Rxjs,Observable,我有一个角度组件,可以在列表中选择项目。因此,onInit()应该执行以下操作: 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
onInit()
应该执行以下操作:
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];
}
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
和可观测值来实现同样的目标。到目前为止,我已经做了以下工作:
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()
,我被困在那里了
更新:
我希望避免在.subscribe()
块中包含this.setDefaultSelectedItem()的内容,如下所示:
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();
});
}
编辑:
解决方案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!`),
});
}
然后,在完整的方法中,你们可以做你们想做的任何事情
如果您有任何疑问,请务必告诉我。我当然知道,但我希望将逻辑保留在小的单一责任块中。我希望loadItems()
只是加载项目,而不是执行所有操作(在本例中也选择default)。当然,这会解决我的问题,但我想知道如何能够使用可观测值来链接函数。如果不是单行函数(this.selectedItem=this.items[0]
),而是有更复杂的逻辑呢?我想在单独的功能中实现它,并因此链接它们。检查新版本。