8

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.
}
Guerric P
  • 30,447
  • 6
  • 48
  • 86
Kyle Vassella
  • 2,296
  • 10
  • 32
  • 62
  • 1
    Possible duplicate of [Angular 2 - Return data directly from an Observable](https://stackoverflow.com/questions/37867020/angular-2-return-data-directly-from-an-observable) – user184994 Aug 29 '18 at 15:31
  • `toPromise` and `await` can do the job. – Baruch Aug 29 '18 at 15:32

4 Answers4

7

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") 
}
Sachila Ranawaka
  • 39,756
  • 7
  • 56
  • 80
6

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).

Tim Klein
  • 2,538
  • 15
  • 19
4

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.

Guerric P
  • 30,447
  • 6
  • 48
  • 86
1

If you have an observable that provides data to populate a table, the best way is not to use subscribe(), but use the observable directly in your html template by using the async pipe. You'll have less to worry about and your code will be much simpler.

edwin
  • 2,643
  • 20
  • 17