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

What you probably want to do is to populate another Observable with the data so that you can access it elsewhere in your project without the need for calling the API more than once.

To do this, you create what is known as a Subject (in this case a BehaviorSubject) and you can populate that with data when your API call returns a response.

Then, in order to access this data elsewhere, you can create a "get" function to return the Subject (which is itself an Observable) whenever you need the data.

Here is an example:

my-data.service.ts

myData: BehaviorSubject<number> = new BehaviorSubject<number>(0);

callApi() {
    this.dbService.get('apiUrl').subscribe(
        (data) = > this.myData.next(data) // Assuming data is a 'number'
    );
}

getMyData() {
    return this.myData.asObservable();
}

Now to use this in a component:

this.myService.getMyData().subscribe(
    (data) => { /* Use the value from myData observable freely */ }
);

Or you could rely on the Angular async pipe (which is a very convenient method for dealing with observables in your code).


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") 
}

You should not subscribe to the Observable inside getData2. Return it as is instead, then do the following:

var dataSource;
this.getData2().subscribe(res => dataSource = res);

Please note that the variable dataSource will be set when the request is done (asynchronously), so you can't use it immediately in the same block scope.

If you want to use it immediately, then put your code inside the subscription.