我正在做一个非常简单的NgRx实现,现在正在为一个组件做get。根据Redux Devtool,数据来自有效载荷,但我似乎无法通过异步管道访问它。
Devtool:
--- ---- UPDATE
问题是当我访问我的ts文件中的切片时,我收到错误
类型'"网络"'不能分配给类型的参数 '"开始"'
ts文件
constructor(private store: Store<fromApp.AppState>) {}
getDns() {
// reach out to ngrx store
this.dnsServers$ = this.store.select('network').map(network => network.dns)
console.log(this.dnsServers$)
// get current dns IPs'
this.networkService.getDns()
.subscribe(
(dnsList: Dns) => {
console.log(dnsList.dns);
this.store.dispatch(
new LoadIpSuccessAction(dnsList.dns)
)
}
)
}
我的功能模块
StoreModule.forFeature('network', { dns: dnsReducer })
我的root reducer(我没有任何模块没有加载懒惰,所以我的root reducer是空的...不知道怎么让它工作否则)
import { Action } from '@ngrx/store';
export interface State {
start: string;
}
const initialState: State = {
start: ''
}
export function startReducer(state = initialState, action: Action) {
return state;
}
和我更新的功能减少器访问dns数组
import * as NetworkActions from './network.actions';
import * as fromApp from '../../store/app.reducers';
export interface NetworkState extends fromApp.AppState {
dns: DnsState;
}
export interface DnsState {
dns: string[];
}
const initialState: DnsState = {
dns: []
}
export function dnsReducer(state = initialState, action: NetworkActions.DnsActions) {
switch (action.type) {
case NetworkActions.LOAD_IP_SUCCESS:
return {
...state,
dns: [...action.payload]
}
default:
return state;
}
}
答案 0 :(得分:2)
在构造函数中,store
指的是整个应用状态,而不仅仅是network
。它应该是
constructor(..., private store: Store<fromApp.AppState>) {}
您需要使用
访问它this.dnsServers$ = this.store.select('network').map(network => network.dns);
此外,action.payload
为{dns: ["6.7.7.7", "5.5.5.5"]}
。当你在reducer中分配它时,你正在dns: [action.payload]
,所以你最终得到的是NetworkState
:
{
dns: [
{ dns: ["6.7.7.7", "5.5.5.5"] }
]
}
如果要在每次想要切片状态时减少构造函数中的逻辑,可以使用选择器:
import { createFeatureSelector, createSelector } from "@ngrx/store";
export const selectNetwork = createFeatureSelector<fromNetwork.NetworkState>('network');
export const selectNetworkDns = createSelector(selectNetwork, (state) => state.dns);
在构造函数中使用它:
constructor(private store: Store<fromApp.AppState>) {
this.dnsServers$ = this.store.select(selectNetworkDns);
}