Problem not get using google API with Angular

1

I have an angled application that should search the Google API for long and lat.

I created this method below to set up my call HTTP.GET() :

ObterGeolocalizacao(): Observable<any> {
    const cep = this.formulariServices.ObterFormulario().dadosPessoais.cep;

    return this.http.get('${API_GOOGLE}cep${KEY_GOOGLE}').map(response => response.json());
}

In my component that will perform this method, I created a variable of type any , like this:

googleGeo: any;

At the click of a button I call the method this way:

try 
{
    this.googleGeoService.ObterGeolocalizacao().subscribe(res => this.googleGeo = res);

    console.log(this.googleGeo);
} 
catch (error) 
{
    console.log(error);
}

She does not make a mistake. However, when I give console.log(this.googleGeo); to view the received data, it comes as undefined .

Could someone please help me?

Thank you in advance ...

    
asked by anonymous 07.06.2018 / 16:26

1 answer

1

The value only exists inside the subscribe because it is asynchronous.

try 
{
    this.googleGeoService.ObterGeolocalizacao().subscribe(res => {
       this.googleGeo = res
       console.log(this.googleGeo); //existe aqui pois o http e assíncrono
});

    console.log(this.googleGeo); //aqui o http ainda não retornou.
} 
catch (error) 
{
    console.log(error);
}
    
07.06.2018 / 16:36