尝试将Observable对象的属性传递给组件,如下所示:
<bookmark [type]="'store'" [targetId]="(store | async)?.id" [endDate]="99999999999999"></bookmark>
但是targetId始终是未定义的。正确的方法是什么?
您做得对,但我想您正面临另一个问题。
让我在这里演示一下: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);
}
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句