我已经在 Angular (版本5.2.9)应用程序中使用ngrx/store(版本5.2.0)和 typescript 版本(2.5.3)实现了状态管理。
当我尝试选择商店并订阅它时遇到问题。
error TS2345: Argument of type '"appStateData"' is not assignable to parameter of type '"appState"'.
app.module.ts
import { StoreModule } from '@ngrx/store';
import { appReducer } from "./store/app.reducers";
...
imports: [
BrowserModule,
FormsModule,
...
StoreModule.forRoot({ appStateData: appReducer }),
],
reducer
import * as AppActions from "./app.actions";
export interface AppState {
appState: State;
}
export interface State {
values: [
{
modalStatus: boolean;
searchString: string;
chemString: string;
}
];
}
const intialState: State = {
values: [
{
modalStatus: false,
searchString: null,
chemString: null
}
]
};
export function appReducer(state = intialState, action) {
switch cases for all actions
...
}
我的组件并订阅商店
import { Component, OnInit } from "@angular/core";
import { Store } from "@ngrx/store";
import * as fromAppReducer from "../store/app.reducers";
export class ResultComponent implements OnInit {
constructor(public store: Store<fromAppReducer.AppState>) {}
ngOnInit() {
this.store.select('appStateData').subscribe(data => {
this.searchString = data.values.slice(-1)[0].searchString;
});
}
}
最佳答案
您的问题来自于:
export interface AppState {
appState: State;
}
还有这个:
constructor(public store: Store<fromAppReducer.AppState>) {}
在构造函数中,您告诉组件预配置存储区具有与接口(interface) AppState
一致的状态片段。接口(interface)AppState
有一个成员,也称为appState
。 Typescript 编译器通过告诉你只能选择存在的状态片来帮助你——在本例中,这是一个名为 appState
的字符串“类型”。
因此,您需要更改此设置:
this.store.select('appStateData')
对此:
this.store.select('appState')
然后订阅并获取值。
一般来说,更好的选择是使用选择器,详细信息如下:
https://github.com/ngrx/platform/blob/master/docs/store/selectors.md
关于javascript - Angular/ngrx 存储 : argument of type 'mystate' is not assignable to parameter of type,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49494029/