如何在ngrx/effects中访问解析器数据? (v7) [英] How to access Resolver Data in ngrx/effects? (v7)

查看:91
本文介绍了如何在ngrx/effects中访问解析器数据? (v7)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在耗时的组件中有 api调用,因此我实现了

I have api calls in the component which is time taking, so i have implemented resolver. I want the resolver data to be present in the store, for later use. I have implemented ngrx/store, ngrx/effects and ngrx/router-store.

组件中的当前状态

  • 直接从组件中的解析器数据获取数据(路由的类型为ActivatedRoute)
  • getting data directly from resolver data in component (route is of type ActivatedRoute)

所需状态

要保存解析器数据,我需要访问生效的解析器数据.所以我可以简单地在组件中调度动作并订阅状态.

To keep the resolver data in store, I need to access resolver data in effects. So i can simply dispatch action in component and subscribe the state.

  • 组件中的调度动作(LoadSubTopicDetails)
  • 效果将监听动作并访问效果中的相同解析器数据

在CustomSerializer的数据"中,我总是空着{}.

I am always getting empty {} in "data" in CustomSerializer.

  • 在app-routing.module.ts中使用解析器

控制台输出


reducers/index.ts(CustomSerializer)

export interface RouterStateUrl {
  url: string;
  queryParams: Params;
  params: Params;
  data: any;
}

export const reducers: ActionReducerMap<State> = {
  routerReducer: fromRouter.routerReducer
};

@Injectable()
export class CustomSerializer implements fromRouter.RouterStateSerializer<RouterStateUrl> {
  serialize(routerState: RouterStateSnapshot): RouterStateUrl {
    let route = routerState.root;
    while (route.firstChild) {
      route = route.firstChild;
    }

    const { url, root: { queryParams } } = routerState;
    const { params, data } = route;
    console.log('routerData in CustomSerializer', { url, queryParams, params, data });

    return { url, queryParams, params, data };
  }
}

reducers/router.selector.ts

export const getRouterState = createFeatureSelector< RouterReducerState<RouterStateUrl> >('routerReducer');

component.ts

// current state of component
this.subTopicDetails = this.route.snapshot.data['content'];

// new way (desired state), getting "resolver data" from store
this.store.dispatch(new fromCourse.LoadSubTopicDetails);
this.store.select(getSubTopicDetails)
          .subscribe(data => this.subTopicDetails = data);

推荐答案

您的效果无法(也应该)访问解析器.

Your Effects can't (and shoudn't) access the resolvers.

解析器应该检查商店中是否有东西,如果没有,应该调度一个操作来检索数据.

The resolvers should check if there is something in the store, and if there isn't it should dispatch an action to retrieve the data.

Todd Motto在 https://toddmotto中提供了一些很好的示例,很好地说明了这一点. com/preloading-ngrx-store-route-guards .

Todd Motto explains this very well with some good examples at https://toddmotto.com/preloading-ngrx-store-route-guards.

这篇关于如何在ngrx/effects中访问解析器数据? (v7)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆