如何在NgRx中选择多个状态

时间:2019-12-23 06:59:24

标签: angular ngrx angular8 ngrx-store ngrx-entity

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

所以要选择我的userPagination状态并将其分派到loadUsers动作中。

如何在此解析器中添加多个选择,然后分派该动作?

3 个答案:

答案 0 :(得分:1)

您可以使用withLatestFrom来获取状态的另一部分:

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

答案 1 :(得分:0)

您可以尝试 combineLatest

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

答案 2 :(得分:0)

使用 withLatestFrom

{{1}}