Smokey Dawson
Smokey Dawson

Reputation: 9240

combine multiple ngrx store selections into single call Angular 7

I basically need to do 3 calls to my ngrx store

So What I had was

getUserInfo() {
    this._store.select('userInfo')
       .subscribe(result => this.userInfo = result);
}

getCats() {
    this._store.select('cats')
       .subscribe(result => this.cats = result);
}

getDogs() {
    this._store.select('dogs')
        .subscribe(result => this.dogs = result);
}

now I'm trying to condense this into a single method so I tried this

I am importing the rxjs like so

import { combineLatest } from 'rxjs';
import { tap, filter } from 'rxjs/operators';

and this is my method

getStoreData() {
    combineLatest(
        this._store.select('userInfo'),
        this._store.select('cats'),
        this._store.select('dogs')
    ).pipe(tap(([userInfo, cats, dogs]) => console.log(userInfo, cats, dogs));
}

I am calling my method like so

ngOninit() {
   this.getStoreData()
}

my issue is the method is being called but I never get the console log?

I'm not sure what I'm doing wrong

EDIT

I have also tried

getStoreData {
    forkJoin(
      this._store.pipe(select('userInfo')),
      this._store.pipe(select('xberts')),
      this._store.pipe(select('tasks'))
    ).subscribe(res => console.log(res));
}

but still the same issue, no console.log()

Any help would be appreciated!

Upvotes: 4

Views: 3805

Answers (2)

delashum
delashum

Reputation: 821

I think you need to subscribe. try either this:

getStoreData() {
    combineLatest(
        this._store.select('userInfo'),
        this._store.select('cats'),
        this._store.select('dogs')
    ).pipe(filter(e => !e.includes(null)),tap(([userInfo, cats, dogs]) => console.log(userInfo, cats, dogs))
    .subscribe()
}

or

ngOninit() {
   this.getStoreData().subscribe()
}

Upvotes: 5

user4851087
user4851087

Reputation:

You can use forkJoin for your scenario

Example:

   forkJoin(
            this.store.pipe(select('userInfo')),
            this.store.pipe(select('cats')),
            this.store.pipe(select('dogs'))
        ).subscribe(res => { });

Something like this

export const selectUser = createSelector(
    userState,
    state => state.user
);

Upvotes: 0

Related Questions