0
votes

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'
    }
1
You are saying that if you place a console.log('something'); right by this.event = event, it will print 'something' to the console as expected? Also, console.log(this.event); <-- this is 'undefined' seems natural to be undefined at that point because the subscriber function has just been set up, therefore most probably not yet executed (this won't affect the fact that that ngIf should become true eventually when the function executes). - acdcjunior
to add to what @acdcjunior just mentioned - try to add <pre>{{ event }}</pre> to your template and see if the actual value changes from false to true. - Tamas

1 Answers

0
votes

Only explanation here is that event in the subscribe is not coming down properly. You will see that event is undefined if you try to print it in the subscribe block

...subscribe((event: Event) => {
   console.log(event); // this will print undefined most likely
});

Then you have to fix your EventBus service