How to refactor to remove the control statements from @ngrx effects?

浪尽此生 提交于 2019-12-12 01:48:28

问题


I have a if control statement in an effect to return an action in the case of data has been retrieved from a service, if not return another action to get data from another Web API. It is a chained effects operation where there is another effect to handle the LOADFROMWEBAPI action.

Is there a better way and avoid the if control statement, and return one action like LoadFromWebAPI only? Where the action SearchCompleteAction can be returned is the question - in effect or reducer?

@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:


@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([])));
  });


来源:https://stackoverflow.com/questions/43597070/how-to-refactor-to-remove-the-control-statements-from-ngrx-effects

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!