【发布时间】:2018-05-11 20:01:04
【问题描述】:
我正在寻找改进以下代码的想法,我将从描述问题开始并给出我希望改进的解决方案。
代码是 Angular 4 (TS)
herelistOfItems$: Observable<Array<Item>>;
// Getting list of items from the backend
init() {
this.listOfItems$ = http.get('/getItems');
}
// - Check if item already exits (show error and stop if exists)
// - If not add the item (http request)
// - Refresh by getting get the updated list from the backend (http request)
onClickAddNewItem(newItem: Item) {
this.listOfItems$ = this.listOfItems$
.filter(/* validate item is not exits */)
.concatMap(_ => http.post('/addItem', newItem))
.switchMap(_ => http.get('/getItems'))
.catch((err) => ...);
}
HTML 代码看起来像
<div *ngFor="let item of listOfItems$ | async">...
这段代码的问题在于递归赋值this.listOfItems$ = this.listOfItems$...
一种可能的解决方案是
onClickAddNewItem(newItem: Item) {
this.listOfItems$
.filter(/* validate item is not exits */)
.concatMap(_ => http.post('/addItem', newItem))
.subscribe(_ => this.listOfItems$ = http.get(...), err => ... );
}
我正在寻找一种更优雅的方式来刷新列表而不订阅它,有什么想法吗? (我知道我可以用 ngrx\store 解决它,但我没有在这个项目中使用它)
感谢您的帮助
【问题讨论】:
-
我不确定您是否要将
switchMap用于addItem,因为如果在尝试添加下一个项目之前未完成上一个项目添加,这将取消它。 -
好点,因为这是 HTTP 请求,我不担心请求被另一个事件取消(只有一个响应事件)但是更好的做法是,我已将示例更改为使用
concatMap
标签: angular typescript rxjs observable ngrx