代码之家  ›  专栏  ›  技术社区  ›  Smokey Dawson

将多个ngrx存储选择组合成单个呼叫7

  •  0
  • Smokey Dawson  · 技术社区  · 7 年前

    ngrx 商店

    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 回复  |  直到 7 年前
        1
  •  4
  •   delashum    7 年前

    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()
    }
    
        2
  •  0
  •   user4851087 user4851087    7 年前

    您可以在您的场景中使用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
    );