如何有效地结合存储状态读取MergeMap中的观察者?

时间:2019-11-05 19:55:04

标签: angular rxjs ngrx ngrx-store ngrx-effects

我想处理有效的动作并根据最新状态执行一些逻辑。有一些示例,但是我在正确接收MergeMap中的数据时遇到问题。

@ ngrx /商店8.1。

@Injectable()
export class SitesEffects {

    constructor(
        private sitesService: SitesService,
        private actions$: Actions, 
        private store: Store<AppState>) {
    }


    getDataForSites$: Observable<Action> = createEffect(() =>
        this.actions$.pipe(
            ofType(LoadSites),
            map(action => action.siteIds), //siteIds is string[]
            withLatestFrom(siteIds => this.store.select(selectSites, new SiteIds(siteIds))), // items return from selector are Site[]
            mergeMap(([a,b]) => {
                // do some logic based on current state
                console.log(a);
                console.log(b);
                return of(SitesLoaded(new Sites([])));
            })

        )
    );
}

我希望'a'是第一个地图函数(字符串数组)的siteIds b是站点数组(withLatestFrom中的Site []) 但 b在Visual Studio代码中有错误

  

类型“可观察”必须具有“ Symbol.iterator”方法   返回iterator.ts(2488)

并且在控制台(开发工具)中存在错误TypeError:undefined不是一个函数(对于mergeMap(([[a,b])=>

应如何对齐所有这些功能,以实现我希望在mergeMap运算符中收到的功能?

1 个答案:

答案 0 :(得分:0)

使用switch / merge映射而不是withLatestFrom

  switchMap(siteIds =>   this.store.select(selectSites, new SiteIds(siteIds))).pipe(first(), map(sites => [siteIds, sites])))

您将获得实际状态和ID。使用第一个运算符,您可以使用第一个发射(商店中的最后一个值)来完成内部可观测值