Search code examples
angularngrx

How to linearly get data from NGRX store


I am having a hard time using NGRX's data access patterns cleanly. So right now I am pulling data from my NGRX store like this:

logBooksAndAuthors() {
    const books$ = this.store.select(store => store.books);
    const authors$ = this.store.select(store => store.authors);

    books$.subscribe((books: Book[]) => {
       authors$.subscribe((authors: Authors[]) => {
            console.log(books);
            console.log(authors);
        });
    });
}

Depending on the business logic, getting data from the store this way can result in very deeply nested callbacks. Ideally, I would want to rewrite the subscriptions in a much more linear manner:

    const books$ = this.store.select(store => store.books);
    const authors$ = this.store.select(store => store.authors);

    const books = books$.subscribe((books: Book[]) => {
        return books;
    });

    const authors = $authors.subscribe((authors: Author[]) => {
        return authors;
    });

    console.log(books); // logs out a subscriber
    console.log(authors); // logs out a subscriber
}

I understand that my code above won't work because books and authors are assigned to subscribers in this case, but I wanted to point out how I'd ideally write the code. Thank you in advance and please let me know if I can clarify my question.


Solution

  • Each this.store.select will return a stream. Since we have two streams here, to make them linear, we should combine them. RxJS has many combination operators.

    Here is example using combineLatest

    logBooksAndAuthors() {
      combineLatest([
        this.store.select(store => store.books),
        this.store.select(store => store.authors)
      ]).subscribe(([books, authors]) => {
        console.log(books, authors)
      })  
    }
    

    Check the other combination operator to suit your case here https://www.learnrxjs.io/learn-rxjs/operators/combination