【发布时间】:2017-08-10 20:27:24
【问题描述】:
我正在尝试在我的 ngrx 商店中存储一个 OrderState 对象。我遇到的问题是将数据从中提取到我的 UI。我只想使用异步管道从这个可观察对象中获取子属性。
order.state.ts
export interface OrderState {
stage: number;
postcode: string;
}
app.component.ts
...
export class AppComponent {
counter: Observable<number>;
readonly orderState$: Observable<OrderState>;
constructor(
private appStateStore: Store<AppState>,
private counterActions: CounterActions,
private orderStateStore: Store<OrderState>,
private orderActions: OrderActions,
) {
this.counter = appStateStore.select('counter');
this.orderState$ = orderStateStore.select(store => store);
}
...
app.component.html
<div>Stage: {{ (orderState$ | async)?.stage }}</div>
从我的orderstate 对象获取stage 属性所需的语法是什么。
如果我显示{{ orderState$ }},我只会在页面上显示[Object object]。
我猜我可能没有从我的商店中正确选择?
更新:我必须在这里遗漏一些基本的东西。我现在已经这样做了,试图弄清楚发生了什么......
app.component.ts
stage: number
...
this.orderStateStore.select(s => s).subscribe((data:OrderState) => {
this.stage = data.stage;
console.log(this.stage);
});
app.component.html
<div>Stage: {{ stage }}</div>
我可以在控制台中看到我的那个阶段报告为未定义。我相信这与问题有关。出于某种原因,我无法在此箭头函数中设置组件的 stage。
更新:这种行为看起来很奇怪...
order.state.ts
export interface OrderState {
stage: number;
postcode: string;
}
app.component.ts
...
this.orderStateStore.select(s => s).subscribe((data:OrderState) => {
console.log('--- START ---');
console.log(data);
console.log('Stage: ' + data.stage);
console.log('--- END ---');
});
...
现在这是我在控制台中得到的...
如您所见,data 实际上不是OrderState 类型。它是OrderState 周围的包装器类型,称为AppState。好的,所以我修改我的代码以记录data.orderState.stage 以获取值1。但是,当我这样做时,TypeScript 抱怨 orderState 不是数据的属性——它显然是在查看控制台输出!
【问题讨论】:
-
{{ (orderState$ | async).stage }} -
遗憾的是没有。不知道我做错了什么。
-
你应该用你的例子创建 plnkr
标签: angular typescript ngrx