如何使用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;
}
}
树view.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));
}
}
我没有抛出任何错误,只是没有任何反应。
答案 0 :(得分:1)
我真的不知道你会得到什么,但我认为这是相似的,并且是你想要达到的目标: https://stackblitz.com/edit/angular-2fukcm
我假设您希望能够在每个节点上展开树。我对你应该做些什么有一个粗略的想法,但我会让你继续在这里看看你发现了什么。
顺便说一下,在你的stackblitz中,app组件中没有<categories></categories>
。此外,您的默认状态缺少“return”:
export function categoryReducer(state: AdminCategory[], action: CategoryActions) {
switch (action.type) {
case ADD_CATEGORY:
return createTreeRecursive([...state, action.payload], 0);
default: return state;
}
}