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.