Amit Sharma
Amit Sharma

Reputation: 758

How to select multiple states in NgRx

@Injectable()
export class UsersResolver implements Resolve<any> {

loading = false;

constructor(private store: Store<AppState>) { }
resolve(route: ActivatedRouteSnapshot,
  state: RouterStateSnapshot): Observable<any> {
    return this.store
    .pipe(
      select(isUserLoaded),
      tap(userLoaded => {
        if (!this.loading && !userLoaded) {
          this.loading = true;
          this.store.dispatch(loadingUsers({
            pagination: {} // **Here i want to get my pagination details from selectUserPagination state**
          }));
        }
      }),
      filter(userLoaded => userLoaded), // only proceed further only in case of coursesLoaded is true
      first(), // Wait for first observable to get values or error
      finalize(() => this.loading = false) // Runs in last
  );
 }
}

So want to select my userPagination state and dispatch it into loadingUsers action.

How to add multiple select into this resolver and then dispatch that action?

Upvotes: 1

Views: 3375

Answers (3)

Claudiu Lazăr
Claudiu Lazăr

Reputation: 43

use withLatestFrom

withLatestFrom(
        this.store.pipe(select(fromRoot.selectLocationName)),
        this.store.pipe(select(fromRoot.selectLocationCode))
      ),
switchMap(([action, name, code]) => {
// do stuff
})

Upvotes: 0

Daniel
Daniel

Reputation: 1422

You can use withLatestFrom to get the other part of your state:

resolve(route: ActivatedRouteSnapshot,
  state: RouterStateSnapshot): Observable<any> {
    return this.store
    .pipe(
      select(isUserLoaded),
      withLatestFrom(this.store.pipe(select(selectUserPagination))), //New Added
      tap(([userLoaded, pagination]) => {
        if (!this.loading && !userLoaded) {
          this.loading = true;
          this.store.dispatch(loadingUsers({
            pagination: pagination // **Here i want to get my pagination details from selectUserPagination state**
          }));
        }
      }),
      filter(userLoaded => userLoaded[0]), // only proceed further only in case of coursesLoaded is true
      first(), // Wait for first observable to get values or error
      finalize(() => this.loading = false) // Runs in last
  );
 }
}

https://www.learnrxjs.io/operators/combination/withlatestfrom.html

Upvotes: 1

Fateh Mohamed
Fateh Mohamed

Reputation: 21357

You can try combineLatest

combineLatest(
 this.store.pipe(select(data1)),
 this.store.pipe(select(data2)),
).pipe(tap(([list1, list2]) => console.log(list1, list2)))

Upvotes: 0

Related Questions