Problem with Subscribe when Return is a single Object

0

I'm developing an angle application 6 and I'm having a problem when I do Subscribe on the method that returns a single object in the HTTP request.

For example, making this request for my component:

 ngOnInit() {

    const empresaId = this.route.snapshot.params['empresaId']
    this.empresaService.getEmpresa(empresaId).subscribe(resp => this.empresa = resp)

    console.log(this.empresa)
  }

My business object gets undefined , but if I put a console log inside the subscribe I'm returning my json normally

I noticed a detail. If I create a type method:

 obterEmpresa() {
    const empresaId = this.route.snapshot.params['empresaId']
    this.empresaService.getEmpresa(empresaId).subscribe(resp => this.empresa = resp)

    console.log(this.empresa)
  }

And I put this method in the button event, on the first click it returns undefined . However, in the second click the object is normally populated with the response.

This problem I'm having only when return is a single object. When it's an array, it works normally.

If you need my service method, there it is:

 getEmpresa(id: number): Observable<Empresa> {
    return this.http.get<Empresa>('${URI}/empresa/${id}')
  }
    
asked by anonymous 20.08.2018 / 22:24

1 answer

4

This is normal, it happens because the request you are making is asynchronous. If you want to give console.log() try something like.

obterEmpresa() {
    const empresaId = this.route.snapshot.params['empresaId']
    this.empresaService.getEmpresa(empresaId).subscribe(resp =>
    {
      this.empresa = resp;
      console.log(this.empresa);
    })
  }

In this way, when the request you made to the server is solved, the subscribe will be executed and the console.log will work.

    
20.08.2018 / 23:40