如何展示商店的内容?
How to display content of store?
我创建了以下商店:
imports: [BrowserModule, StoreModule.forRoot({ bugs: bugsReducer })],
然后我创建了reducer和action:
const addBugAction = createAction('[bbb] add bug', props<Bug>());
export const bugsReducer = createReducer(
{ bugs: [] },
on(addBugAction, (state, bug) => ({
bugs: [...state.bugs, bug]
}))
);
我还有一个选择器:
const selectState = (state: any) => state;
export const selectBugs = createSelector(
selectState,
(state: any) => state.bugs
);
最后我尝试将商店的内容显示到 HTML 模板中:
@Component({
selector: 'app-root',
template: `
<div *ngIf="bugs$ | async">
bugs: {{ (bugs$ | async).bugs }}
</div>
`
})
export class AppComponent {
constructor(private store: Store<any>) {
this.store.dispatch(
addBugAction({
x: 100,
y: 200
})
);
setTimeout(() => {
const bugs$ = this.store.pipe(select('selectBugs'));
bugs$.subscribe(console.log);
}, 1000);
}
}
但我只看到一个白屏。控制台显示
undefined
能帮我展示商店的内容吗?换句话说,我需要在屏幕上显示 bugs 值。
实例是HERE
您只需从选择器中删除引号即可看到这样的控制台日志:
const bugs$ = this.store.pipe(select(selectBugs));
要查看页面上的值,请创建一个 TypeScript class 变量来存储该值并将其绑定到模板中。
我已经更新了你的代码 here。
我创建了以下商店:
imports: [BrowserModule, StoreModule.forRoot({ bugs: bugsReducer })],
然后我创建了reducer和action:
const addBugAction = createAction('[bbb] add bug', props<Bug>());
export const bugsReducer = createReducer(
{ bugs: [] },
on(addBugAction, (state, bug) => ({
bugs: [...state.bugs, bug]
}))
);
我还有一个选择器:
const selectState = (state: any) => state;
export const selectBugs = createSelector(
selectState,
(state: any) => state.bugs
);
最后我尝试将商店的内容显示到 HTML 模板中:
@Component({
selector: 'app-root',
template: `
<div *ngIf="bugs$ | async">
bugs: {{ (bugs$ | async).bugs }}
</div>
`
})
export class AppComponent {
constructor(private store: Store<any>) {
this.store.dispatch(
addBugAction({
x: 100,
y: 200
})
);
setTimeout(() => {
const bugs$ = this.store.pipe(select('selectBugs'));
bugs$.subscribe(console.log);
}, 1000);
}
}
但我只看到一个白屏。控制台显示
undefined
能帮我展示商店的内容吗?换句话说,我需要在屏幕上显示 bugs 值。
实例是HERE
您只需从选择器中删除引号即可看到这样的控制台日志:
const bugs$ = this.store.pipe(select(selectBugs));
要查看页面上的值,请创建一个 TypeScript class 变量来存储该值并将其绑定到模板中。
我已经更新了你的代码 here。