Home > Mobile >  Variable loses it's value once out of API call
Variable loses it's value once out of API call

Time:06-10

I just started to build my first AngularApp by myself. I have watched many tutorials over and over again. But I just can't figure out what I am doing wrong.

I have built apps with PHP and other languages in the past but it seems that Angular does things differently.

The problem is that I am declaring my_var at the start of my code. A couple of lines down I make an API call to get a list of items. I console log the resp and my_var values and it all looks good. When I try to use my_var outside of the API 'loop', it just turns into undefined.

I know I am doing something wrong here. I suspect I have not yet understood how variable scopes work in Angular.

Here is the component code:

rvcs;

constructor(private productService: ProductService, public configService: ConfigService, private apis: APIsService) {}

ngOnInit() {
              
        this.apis.consultarRVCs().subscribe( resp => {
            this.rvcs = resp//stores RESP values - WORKS
            console.log('Value of RESP: ',resp)//prints RESP values - WORKS
            console.log('Value of variable after storing RESP values in it: ',this.rvcs)//prints the value insde this loop/api call - WORKS
          })
        
          
        console.log('Value of variable outside of API call: ',this.rvcs);//prints undefined - Doesn't WORK

Here is the API funcition in the Service file:

consultarPopularidadPorFechaIn(id_rvc,fecha_in) {
    return this.http.get(`${this.API_URL}/consultarReservaciones/${id_rvc}/${fecha_in}`);
  }

As you can see in this picture, the last console log is being printed as undefined before the API call. This is why I suspect it has something to do with variable scopes.

enter image description here

CodePudding user response:

The code you are posting is correct, the results from the console.log are expected.

Angular uses Observables for handle a variety of common asynchronous operations. By default, observables are lazy, if you don't subscribe to them, you will not get the response from the http call in this case.

Once you subscribe, the code within the subscribe function becomes asynchronous, meaning, it will execute later.

...
export class MyComponent implements OnInit {
  constructor(private myService: MyService) {}

  ngOnInit(): void {
    console.log('1');
  
    this.myService.getSomething().subscribe(() => console.log('2'));     

    console.log('3');
  }
}

// Output will be 1, 3, 2

You can read more about observables here: link

CodePudding user response:

async ngOnInit(): void {
  // here console.log will be called only after wait anser from service func
  this.rvcs = await this.apis.consultarRVCs().toPromise().then().catch();
  console.log('Value of variable outside of API call: ',this.rvcs);//prints undefined - Doesn't WORK
}
  • Related