Get problem using google’s Angular API

Asked

Viewed 73 times

1

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

I created this method below to configure 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, in this way:

googleGeo: any;

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

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

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

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

Could someone please help me?

Thank you in advance...

  • Value only exists within subscribe because it is asynchronous.

  • Got it! I tried it here and it really worked! If you want to add a reply I approve here! Thank you so much

1 answer

1


Value only exists within 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);
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.