I'm trying to subscribe to an observable source in order to bind the source's value to a component variable (event: Event).
In spite of the fact that the observer function passed to the subscribe() function executes correctly, and the observable arrives at expected, the component variable event: Event is always undefined.
Why is that happening and how can I solve this problem?
@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'
}
console.log('something');right bythis.event = event, it will print'something'to the console as expected? Also,console.log(this.event); <-- this is 'undefined'seems natural to beundefinedat that point because the subscriber function has just been set up, therefore most probably not yet executed (this won't affect the fact that thatngIfshould become true eventually when the function executes). - acdcjunior