我正在尝试订阅可观察源,以便将源的值绑定到组件变量(event: Event
)。
尽管传递给subscribe()
函数的观察者函数正确执行,并且observable到达预期值,但组件变量event: Event
始终未定义。
为什么会发生这种情况?如何解决这个问题?
@Component({
selector: 'event-detail',
template: `
<div *ngIf="event"> <-- this will never evaluate to 'true'
...
</div>
`,
})
export class EventCenterDetailComponent implements OnInit {
event: Event;
subscription: Subscription;
constructor(
private eventBus: EventBus
) {}
ngOnInit() {
this.subscription = this.eventBus.event$.subscribe((event: Event) => {
this.event = event; <-- this assignment seems to have no effect on the component variable
});
console.log(this.event); <-- this is 'undefined'
}
答案 0 :(得分:0)
这里只有解释是订阅中的event
没有正常下来。如果您尝试在订阅块中打印它,您将看到event
未定义
...subscribe((event: Event) => {
console.log(event); // this will print undefined most likely
});
然后您必须修复EventBus
服务