bellotas
bellotas

Reputation: 2461

Subscribe - Angular 2

I have a file where I code my whole connection with the REST service, and it works.

From another file, I am executing the following lines (everything works)

 this.baseService.getCars(ID)
    .subscribe(cars=> this.cars= cars);

To access to the values of the response I was using HTML. For example: *ngIf="cars"

Now, I would like to access by Javascript to the variable doing this:

this.baseService.getCars(ID)
        .subscribe(cars=> this.cars= cars);
console.log(this.cars) 

but I get undefined but I can access by HTML. I know that it is a stu**d question, but how should I do it? Which variable does contain the variable?

Upvotes: 1

Views: 68

Answers (3)

fer.reyes4
fer.reyes4

Reputation: 129

Subscribe is asynchronous, like a Promise, but isn't a Promise so, when you execute the code, the subscribe is fired, then the console log. But When the console.log is executing, subscribe is running yet, so that's why you get undefined.

You can do the console.log inside the callback function in subscribe

this.baseService
    .getCars(ID)
    .subscribe(cars=> {
        this.cars = cars
        console.log(this.cars)
    });

Another solution is to use async/await. You can't use async/await directly with subscribe, because IT'S NOT A PROMISE. Fortunately Observers can be converted to a Promise.

So, in you service you can return a promise, like this:

getCars() {
    // your service stuff
    return this.api.get(url).toPromise().then( res => res.data); // This is the important part.
}

Then, in your component, call it with async/await:

async yourFunction() {
    this.cars = await this.baseService.getCars(ID);
    console.log(this.cars);
}

Now you can log this.cars after the getCars()

Hope this helps you.

Upvotes: 1

Sajeetharan
Sajeetharan

Reputation: 222582

You need to place the console.log inside subscribe

  this.baseService.getCars(ID)
  .subscribe(
    cars=> {
      this.cars= cars;
      console.log(this.cars);
    },
    error => {
      console.log(error);
    }
  );

Upvotes: 1

Uğur Dinç
Uğur Dinç

Reputation: 2455

The execution order of those lines of code is not what you think it is.

To see cars in console, change your function to this:

this.baseService.getCars(ID)
        .subscribe(cars=>{ 
    this.cars= cars;
    console.log(this.cars);
});

Upvotes: 3

Related Questions