jus*_*oob 7 javascript rxjs angular
在我的Angular服务中,我有以下方法:
// creates an Item and returns the ID of the created Item
createItem(item: Item): Observable<ItemId> {
return this.http.post<ItemId>('some_api_url', item);
}
// returns all Items
getAllItems(): Observable<Item[]> {
return this.http.get<Item[]>('some_api_url');
}
Run Code Online (Sandbox Code Playgroud)
在我的模板中,我显示列表中的项目.
我希望能够创建一个新项目,然后重新加载列表(包括新创建的项目),所以我实现了以下内容:
this.itemService.createItem(item)
.pipe(
switchMap(createdId => this.itemService.getAllItems())
).subscribe(result => {
this.items = result;
});
Run Code Online (Sandbox Code Playgroud)
这似乎工作正常,但最后我还想做一些处理createdId:
this.itemService.createItem(item)
.pipe(
switchMap(createdId => this.itemService.getAllItems())
).subscribe(result => {
this.items = result;
// i would like to use createdId here as well
});
Run Code Online (Sandbox Code Playgroud)
所以我想出了以下内容:
this.itemService.createItem(item)
.pipe(
switchMap(createdId =>
combineLatest(this.itemService.getAllItems(), of(createdId)))
).subscribe(result => {
this.items = result[0];
// doing some stuff with result[1], which is the value of createdId
});
Run Code Online (Sandbox Code Playgroud)
但是必须在combineLatest内部使用switchMap并明确地制作createdId一个Observable让我想知道这是否是一个很好的解决方案.
所以基本上我想创建和项目,更新列表(当项目创建完成时)并在更新完成时使用创建项目的ID.
有一个更好的方法吗?
我真的很感激任何建议.
在深入研究 RxJS 运算符后,我认为最干净的解决方案可能是简单地concat与以下内容结合使用toArray:
// import { concat } from 'rxjs';
// import { toArray } from 'rxjs/operators';
concat(
this.itemService.createItem(item),
this.itemService.getAllItems())
.pipe(toArray())
.subscribe((result: [ItemId, Item[]]) => {
// result[0] is the ItemId
// result[1] is the Item[]
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
121 次 |
| 最近记录: |