簡體   English   中英

如何在 NgRx 中選擇多個狀態

[英]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
  );
 }
}

所以想選擇我的 userPagination 狀態並將其分派到 loadingUsers 操作中。

如何將多個選擇添加到此解析器中,然后調度該操作?

您可以使用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

你可以試試combineLatest

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

使用withLatestFrom

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM