有条件地发射 observable

Conditionally emit observable

我们有一个带有 Redux (ngrx 4) 的 Angular 4 应用程序。

我们将信息"isLoggedIn"保存在ngrx/store中,当我们向http发出调用时,我们必须首先检查他是否已通过身份验证。

我们正在努力解决的是进行 http 调用的服务的实现:

export class GetDataFromREST() {

     constructor(private http: HttpClient, private loginStore: Store) {
          this.loggedIn$ = this.loginStore.select(getLoggedIn);
     }
     ...
     public getProducts(): Observable<ProductList> {

          return /*observable that returns http.get(api) only 
                   after the loggedIn$ emits true */
     }
}

请注意,登录不应该是该服务的关注点 - 一旦登录,它应该执行从它那里请求的所有调用。

有什么想法吗?

使用 CombineLatest 运算符将 log in observable 与 get api observable 结合起来,然后您可以按登录状态进行过滤

http://reactivex.io/documentation/operators/combinelatest.html http://reactivex.io/documentation/operators/filter.html

这将达到您要求的结果。

export class GetDataFromREST() {

     constructor(private http: HttpClient, private loginStore: Store) {
          this.loggedIn$ = this.loginStore.select(getLoggedIn);
     }
     ...
     public getProducts(): Observable<ProductList> {

          return this.loggedIn$.filter(Boolean).take(1).subscribe(
            () => http.get(api)
          )
     }
}

因为 loggedIn$ 已经是一个 Observable,你可以重放它的最后一个值并将它用作将与远程调用合并的源 Observable:

this.loggedIn$ = this.loginStore.select(getLoggedIn)
  .publishReplay(1)
  .refCount();

...

public getProducts(): Observable<ProductList> {
  return this.loggedIn$
    .mergeMap(() => http.get(api));
}

所以 getProducts()this.loginStore.select(getLoggedIn) 发出之前不会发出任何东西。

此外,当您稍后调用 getProducts() 时,this.loggedIn$ 中的最新值将被重播,因此它会立即 运行 远程调用。