将多个ngrx存储选择合并到单个调用Angular 7中

时间:2019-04-05 03:49:08

标签: angular typescript rxjs

我基本上需要对我的ngrx商店进行3次呼叫

所以我曾经是

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

现在我正在尝试将其压缩为一个方法,所以我尝试了

我正在这样导入rxjs

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

这是我的方法

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

我正在这样调用我的方法

ngOninit() {
   this.getStoreData()
}

我的问题是该方法正在被调用,但是我从未获得控制台日志?

我不确定自己在做什么错

编辑

我也尝试过

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

但还是同样的问题,没有console.log()

任何帮助将不胜感激!

2 个答案:

答案 0 :(得分:0)

您可以在方案中使用forkJoin

示例:

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

类似这样的东西

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

答案 1 :(得分:0)

我认为您需要订阅。尝试以下任一方法:

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()
}

ngOninit() {
   this.getStoreData().subscribe()
}
相关问题