Angular 6 observables - extract data from .subscribe() function and use it elsewhere

Kyle Vassella picture Kyle Vassella · Aug 29, 2018 · Viewed 15.9k times · Source

I'm banging my head against the wall with observables. Almost all of the documentation I can find is in the older rxjs syntax.

I have an API call which is an observable. I'm calling it elsewhere and subscribing to it - trying to populate a table with the data from this GET request.

If I simply console.log my getData function, it logs the subscription rather than my data. I can successfully console.log data within the .subscribe function, but I want to use data outside of .subscribe().

How do I extract data out of the .subscribe() function and use it elsewhere? Or, must all of my logic be contained within the .subscribe() function to use data?

getData2() {
    return this.m_dbService.get('api/myApiPath').subscribe(
        data => (console.log(data)), //This properly logs my data. How to extract `data` out of here and actually use it?
        error => { throw error },
        () => console.log("finished")
    );
}

workbookInit(args){
     var datasource = this.getData2();   // this returns the subscription and doesn't work.
}

Answer

Sachila Ranawaka picture Sachila Ranawaka · Aug 29, 2018

just return the HTTP req from getData() and subscribe it inside the workbookInit function.

getData2() {
    return this.m_dbService.get('api/myApiPath')
}

workbookInit(args){
    this.getData2().subscribe(
        data => {
           var datasource = data 
        }, 
        error => { throw error },
        () => console.log("finished") 
}