为什么要对Http服务使用.takeUntil()而不是.take(1)? [英] Why use .takeUntil() over .take(1) with Http service?

查看:74
本文介绍了为什么要对Http服务使用.takeUntil()而不是.take(1)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

上下文:我正在努力在一个环境中实现 @ ngrx/effects @ ngrx/store 项目并研究

Context: I am working on implementing @ngrx/effects within an @ngrx/store project and studying the example app.

问题:在 BookEffects类文件,第50行,为什么使用takeUntil(...)代替take(1)?在这种情况下,两者似乎都可以完成相同的事情.

Question: In the BookEffects class file, line #50, why is takeUntil(...) used instead of take(1)? Both would seem to accomplish the same thing in this case.

@Injectable()
export class BookEffects {
  constructor(private actions$: Actions, private googleBooks: GoogleBooksService) { }

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

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

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

这是

推荐答案

要理解为什么使用takeUntil,可能不做任何关于searchBooks实现的假设.

To understand why takeUntil is used, it might help to make no assumptions about the implementation of searchBooks.

searchBooks服务方法返回一个可观察的Book[].该可观察性不一定必须完成.例如,如果数据库发生更改,它可能会发出其他结果(Firebase的AngularFire2可观察对象就是这种情况).但是,如果使用take(1),后续结果将被忽略.如果使用takeUntil,后续结果将继续起作用,直到启动下一次搜索为止.

The searchBooks service method returns an observable of Book[]. That observable does not necessarily have to complete; for instance, it could emit additional results if the database changes (this is what happens with Firebase's AngularFire2 observables). However, if take(1) is used, subsequent results will be ignored. If takeUntil is used, subsequent results will continue to effect actions until the next search is initiated.

但是,我不认为takeUntil是必不可少的,因为switchMap会处理所有事情(内部可观察对象将不再被订阅,等等).

However, I don't think the takeUntil is essential, as the switchMap will take care of things (the inner observable will be unsubscribed, etc.).

example-app的作者似乎已经实现了搜索效果,而不依赖于服务的实现.

The author(s) of the example-app appear to have implemented the search effect in such a way that it is not dependent upon the implementation of the service.

使用searchBooks的基于Http的简单实现,我看不到为什么需要take(1)takeUntil-因为可观察对象将完成,并且switchMap将确保SearchCompleteAction不会进行过时搜索操作.

With the simple, Http-based implementation of searchBooks, I cannot see why either take(1) or takeUntil would be required - as the observable will complete and the switchMap will ensure that SearchCompleteAction actions for stale searches are not emitted.

这篇关于为什么要对Http服务使用.takeUntil()而不是.take(1)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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