如何重构从@ngrx效果中删除控制语句?

时间:2017-04-24 20:21:25

标签: angularjs ngrx

我在效果中有一个if控制语句,用于在从服务检索数据的情况下返回操作,如果没有返回另一个操作以从另一个Web API获取数据。这是一个链式效果操作,其中有另一个效果来处理LOADFROMWEBAPI操作。

是否有更好的方法并避免使用if控制语句,并仅返回LoadFromWebAPI之类的操作?可以返回动作SearchCompleteAction的是问题 - 实际还是减速器?

@Effect()
  search$: Observable<Action> = this.actions$
    .ofType(book.SEARCH)
    .debounceTime(300)
    .map(toPayload)
    .switchMap(query => {
      if (query === '') {
        return empty();
      }

      const nextSearch$ = this.actions$.ofType(book.SEARCH).skip(1);

      return this.googleBooks.searchBooks(query)
        .takeUntil(nextSearch$)
        .map(books => {
        if (data === undefined) { 
            return new book.LoadFromWebAPI(query); 
        } else { 
            return new book.SearchCompleteAction(books); 
        }
    })
        .catch(() => of(new book.SearchCompleteAction([])));
    });

1 个答案:

答案 0 :(得分:0)

@Effect()
search$: Observable<Action> = this.actions$
  .ofType(book.SEARCH)
  .debounceTime(300)
  .map(toPayload)
  .filter(query => query !== '')
  .switchMap(query => {
    const nextSearch$ = this.actions$.ofType(book.SEARCH).skip(1);
    return this.googleBooks.searchBooks(query)
      .takeUntil(nextSearch$)
      .map(books => data === undefined ? new book.LoadFromWebAPI(query) : new book.SearchCompleteAction(books))
      .catch(() => of(new book.SearchCompleteAction([])));
  });