如何将Observable属性传递给Angular2中的组件?
问题描述:
尝试可观察到的对象的属性传递给组件是这样的:如何将Observable属性传递给Angular2中的组件?
<bookmark [type]="'store'" [targetId]="(store | async)?.id" [endDate]="99999999999999"></bookmark>
但目标ID总是不确定的。什么是正确的方式呢?
答
你这样做是正确的,但我猜你所面对的另一个问题..
让我在这里展示它:https://plnkr.co/edit/AE67JyXZ5hg6A1ahrm7E?p=preview
如果这是一个“正常”的观察到的,认为将只在更新在视图启动后触发事件!
如果有事件发生,它将不会显示!
因此,您应该使用BehaviorSubject
,这将“缓冲”最后一个值。
@Component({
selector: 'my-app',
template: `
<div>
<h2>Hello {{name}}</h2>
<br />
without timeout: {{ (testWoTimeout | async)?.any }} <!-- will not be shown -->
<br />
with timeout: {{ (test | async)?.any }} <!-- will be shown cause of that timeout -->
<br />
behavior subject: {{ (behaviorTest | async)?.any }} <!-- will be shown cause of that BehaviorSubject -->
</div>
`,
})
export class App {
name:string;
test = new Subject();
testWoTimeout = new Subject();
behaviorTest = new BehaviorSubject({ any: 'default' });
constructor() {
this.name = 'Angular2'
}
ngOnInit() {
this.testWoTimeout.next({ any: 'prop' }); // this will not be shown, cause its fired before the view was initiated!
this.behaviorTest.next({ any: 'prop' });
setTimeout(() => {
this.test.next({ any: 'prop' });
}, 250);
}
}
你能分享组件代码吗?另外,你不需要使用异步和?一起。 –
尝试使用'[targetId] =“store?.id | async” –