【问题标题】:rxjs observable - avoid recursive assignmentsrxjs observable - 避免递归赋值
【发布时间】: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


【解决方案1】:

您可以从通常运行onClickAddNewItem 的点击事件创建可观察流。

@ViewChild() addButton;

this.listOfItems$ = this.http.get('/getItems').pipe(
  switchMap(items => fromEvent(this.addButton.nativeElement, 'click').pipe(
    startWith(items),
    filter(/* ... */)
    mergeMap(newItem => this.http.post('/addItem', { newItem })),
    switchMap(() => this.http.get('/getItems')),
  ),
);

【讨论】:

    猜你喜欢
    • 2018-02-24
    • 2018-09-05
    • 2017-01-31
    • 2021-05-13
    • 1970-01-01
    • 1970-01-01
    • 2013-11-10
    • 2021-06-05
    • 1970-01-01
    相关资源
    最近更新 更多