如何重构以从@ngrx效果中删除控制语句? [英] How to refactor to remove the control statements from @ngrx effects?

查看:96
本文介绍了如何重构以从@ngrx效果中删除控制语句?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个if控制语句,其作用是在已经从服务中检索到数据的情况下返回一个动作,如果没有返回另一个动作来从另一个Web API获取数据的话.这是一个连锁效果操作,其中还有另一个效果可以处理LOADFROMWEBAPI动作.

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.

是否有更好的方法来避免使用if控制语句,而仅返回类似LoadFromWebAPI的动作?问题SearchCompleteAction可以返回的地方是问题-是有效的还是化简的?

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

推荐答案

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

这篇关于如何重构以从@ngrx效果中删除控制语句?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆