我在一个 Angular 8 应用程序中有多个项目...
到目前为止,我只有一个项目 @ngrx/store
但
现在我在每个项目中添加了 @ngrx/store
,并且由于有多个商店,我需要在 app.module
中的每个项目中导入 StoreModule.forFeature
imports: [
StoreModule.forRoot({}),
StoreModule.forFeature("project1store", fromStore.reducer1)
]
在第二个项目中,我导入
imports: [
StoreModule.forRoot({}),
StoreModule.forFeature("project2store", fromStore.reducer2)
]
问题是,在 redux 中,我看到了所有数据,但我无法接受。 另外,每个 reducer 都会出现错误(所有这些 reducer 之前都工作过)
store.js:994 @ngrx/store: The feature name "UserProfileReducer" does not exist in the state, therefore createFeatureSelector cannot access it. Be sure it is imported in a loaded module using StoreModule.forRoot('UserProfileReducer', ...) or StoreModule.forFeature('UserProfileReducer', ...). If the default state is intended to be undefined, as is the case with router state, this development-only warning message can be ignored.
我使用桶 (index.ts) 导入所有内容,在本例中是从 fromStore
导入的。
每个应用程序都有自己的桶,我再次检查,每条路径都没有问题...
在这张图片上看,所有数据都在那里,但是现在在StoreModule.forFeature
之后无法获取它
编辑:
在此之前,我得到像 store.siteReducer
这样的数据,但现在我需要像 state.app2.siteReducer
如何以及在何处添加此 app1
或 app2
?
谢谢
编辑2
我可以通过这种方式直接在组件中获取数据
select((state: any) => state.app1.SiteReducer)
.subscribe(res => {...})
但是这样,我需要对整个应用程序组件进行更改。 如何直接在选择器中进行此操作? 我试试这个
export const getState = createFeatureSelector<States>("app1");
export const getSite = createSelector(
getState,
(state: States) => state.app1.siteReducer
);
但出现错误
Property 'app1' does not exist on type 'States'
这是我的状态
export class States {
data: { site: SiteModel | null; error: string };
}
export const InitialState = {
data: { site: null, error: null
}
};
如果我在选择器模型中删除 State
并放置 any
,则一切正常
export const getState = createFeatureSelector<States>("app1");
export const getSite = createSelector(
getState,
(state: any) => state.app1.siteReducer
);
我也尝试在州模型中添加这个
export class States {
siteReducer: {data: { site: SiteModel | null; error: string }};
}
export const InitialState = {
siteReducer: {data: { site: null, error: null }}
};
但现在在商店中我已经嵌套了 siteReducer
对象(下面是示例)
app1{
siteReducer{ // get this parent object
siteReducer:{
data:{..}
}}
}
最佳答案
您需要配置功能选择器才能获取嵌套级别状态
export const selectState = createFeatureSelector<ISomeState>(
"app2"
);
export const selectSomeState = createSelector(
selectState,
state => state.someProp.someProp
);
然后配置你的 reducer
import { ActionReducerMap } from "@ngrx/store";
export interface ISomeState {
userState: IUserState ; // add your state interface here
}
export const reducers: ActionReducerMap<ISomeState> = {
userState: userReducer // your reducer
};
所以你需要将reducer导入到你的模块中
StoreModule.forFeature("app2", reducers)
如果这不起作用,请在 github 上分享您的源代码,我会看看
关于angular - 添加StoreModule.forFeature(...)后无法访问存储的数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59103649/