Search code examples
angularrxjsobservablengrxngrx-store

Conditionally emit observable


We have an Angular 4 app with Redux (ngrx 4).

We keep the info "isLoggedIn" in the ngrx/store, and when we issue a call to the http, we have to first check if he's authenticated or not.

What we're struggling with is the implementation of the service making the http calls:

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 */
     }
}

Note that logging in should not be a concern of the service - once logged in it should execute all calls that were asked from it.

Any thoughts?


Solution

  • This will achieve your requested result.

    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)
              )
         }
    }