【发布时间】:2018-05-09 05:09:43
【问题描述】:
如何使用ngrx/store 使用@Input 属性初始化模板?当我测试addCategory 函数时,它按预期工作,但我希望显示我在初始化类的reducer 中声明的初始状态。
reducer.ts:
export interface AppState {
categoryState: AdminCategory[]
}
export class AdminCategory {
id: number;
name: string;
parentId: number;
constructor(id: number, name: string, parentId: number) {
this.id = id;
this.name = name;
this.parentId = parentId;
}
}
export const ADD_CATEGORY = 'ADD_CATEGORY';
export const REMOVE_CATEGORY = 'ADD_CATEGORY';
export class AddCategory implements Action {
readonly type = ADD_CATEGORY;
constructor(public payload: AdminCategory) { }
}
export class RemoveCategory implements Action {
readonly type = REMOVE_CATEGORY;
constructor(public payload: AdminCategory) { }
}
export type CategoryActions = AddCategory | RemoveCategory
export function categoryReducer(state: AdminCategory[] = [new AdminCategory(1, "asd", 0)], action: CategoryActions) {
switch (action.type) {
case ADD_CATEGORY:
return [...state, action.payload];
default: state;
}
}
树视图.ts:
@Component({
selector: 'categories',
template: `
<div *ngFor="let cat of categories | async">
<ul>
<li>
<span (click)="addCategory(cat)">{{cat.name}}</span>
</li>
</ul>
</div>
`
})
export class TreeView implements OnInit {
@Input() categories: Observable<AdminCategory[]>
constructor(private store: Store<AppState>, private dialog: MatDialog) {}
ngOnInit() {
this.categories = this.store.select('categoryState');
}
addCategory(category: AdminCategory) {
this.store.dispatch(new AddCategory(category));
}
}
我没有抛出任何错误,只是没有任何反应。
【问题讨论】:
-
为什么要同时使用
@Input和ngOnInit来初始化categories? -
我删除了
ngOnInit并将this.categories = this.store.select('categoryState');放到构造函数中。它不会改变任何东西。我只想显示我的初始状态,而不需要用户提供任何操作。现在我只是在 reducer 函数中创建AdminCategory但我们可以想象它是一个 API 调用 -
你试过像
{{ (categories | async) | json }}这样简单的东西吗? -
是的,也没有任何反应。看起来只有
addCategory函数中调度的事件有效。然后它显示带有初始状态的实际存储 +category我将其传递给函数。这很好,但我需要在开始时显示初始状态。我尝试了很多可能的解决方案,花了大约 15 个小时来解决不同的变通办法、后期初始化、文档中的初始状态、一些超时等......我对基本用例很难实现这一点有点失望 -
你能为你的问题创建一个最小的堆栈闪电战吗?