如何在单次调用中组合 Angular ngrx 多重选择

问题描述 投票:0回答:5

如何将两个选择结合到单个函数中。我尝试了几种方法,例如:

combineLatest
,它没有调用其他 stackoverflow 讨论。有什么办法可以同时实现单一功能吗?

constructor(private store: Store<fromStore.AppState>) {}

ngOnInit(): void {
  this.store
    .select("userInfo", "user")
    .pipe(takeUntil(this._unsubscribeAll))
    .subscribe((userInfo) => {
      console.log(userInfo);
    });

  this.store
    .select("cart")
    .pipe(takeUntil(this._unsubscribeAll))
    .subscribe((detail) => {
      console.log(detail);
    });
}
angular rxjs ngrx ngrx-selectors
5个回答

0
投票

为了使用

combineLatest
,每个可观察量必须至少发出一个值。如果您不确定某些可观察量是否发出,可以使用
startWith
运算符来保证可观察量发出第一个值。每当
combineLatest
内的一个可观察量发出新值时,它就会反映变化。

this.userInfo$ = this.store
    .select("userInfo", "user")
    .pipe(startWith(null),takeUntil(this._unsubscribeAll));
    

  this.detail = this.store
    .select("cart")
    .pipe(startWith(null),takeUntil(this._unsubscribeAll));
    

    combineLatest([this.userInfo$, this.detail$]).subscribe(([userInfo,detail])=>{...});

0
投票

您可以使用

combineLatest
运算符来
startWith
,因为每个可观察对象都应该发出至少一个值来执行订阅。

ngOnInit(): void {
  const userInfo$ = this.store.select("userInfo", "user")
                        .pipe(
                          startWith(null),
                          takeUntil(this._unsubscribeAll)
                         );
    
  const cart$ = this.store.select("cart")
                    .pipe(
                      startWith(null),
                      takeUntil(this._unsubscribeAll)
                     );

  combineLatest([userInfo$, cart$])
    .subscribe(([userInfo, cart])=>{ consolse.log(userInfo, cart)});        
}

0
投票

最后我这样做了:

let user$: Observable<any> = null;
let detail$: Observable<any> = null;

user$ = this.store.select('userInfo', 'user');
detail$ = this.store.select('cart');

combineLatest([user$, onboardingId$])
            .pipe(takeUntil(this._unsubscribeAll))
            .subscribe((responses) => {.....}

0
投票

我希望它有效

combineLatest([
            this._store.select(selectIsLoaded),
            this._store.select(selectDeptIsLoaded)])
            .pipe(
                untilDestroyed(this),
                filter(([compIsloaded, deptIsLoaded]) => compIsloaded && deptIsLoaded),
                withLatestFrom(
                    this._store.select(selectCompanies),
                    this._store.select(selectDepartments1),
                    this._store.select(selectDepartments2),
                    this._store.select(selectDepartments3),
                ),
                tap(([_, companies, departments_1, departments_2, departments_3]) => {
                    this.mapStructure({
                        companies,
                        departments_1,
                        departments_2,
                        departments_3,
                    })
                })
            ).subscribe();

© www.soinside.com 2019 - 2024. All rights reserved.