Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Trying to Subscribe to a method that returns an Observable in Angular

I have a method that returns an Observable:

clockOut(): Observable<boolean> {
    let isClockedOut = new Subject<boolean>();
    isClockedOut.next(false);

    // Some code to clock out and return x

    if (x === true) {
        isClockedOut.next(true);
    }

    return isClockedOut.asObservable();
}

And I’m calling/subscribing to the clockOut() method like so:

ngOnInit() {
    this.clockOut().subscribe((didClockOut: boolean) => {
        if (didClockOut === true) {
            // Do stuff
        }
    });
}

The clockOut() method gets called, and the code inside clockOut() executes properly, but the code block after .subscribe is not being called. Almost like clockOut() isn’t returning the Observable?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

I’m new to Angular and I’ve not worked with Observables/Subjects much. Any help is appreciated. Thanks!

>Solution :

The subject does not return old events to new subscriptions, you are triggering, next before returning the observable, so those events are not subscribed yet.

also, you don’t have any need for Subject here since everything is synchronous.

if you want last event triggered you can use BehaviorSubject instead of subject

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading