Subscribe problem when return is a single Object

Asked

Viewed 230 times

0

I am developing an application at angular 6 and am having a problem when I do Subscribe in the method that returns a single object in the HTTP request.

For example, making this request by my component:

 ngOnInit() {

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

    console.log(this.empresa)
  }

My object company is undefined, but if I put a log console inside the subscribe I’m returning my json normally

I noticed a detail. In case 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, the first click returns undefined. However, in the second click the object is normally filled with the answer.

This problem I am having only when the return is a single object. When it is 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}`)
  }
  • this is not a problem but the expected behavior. http being asynchronous the object will only have value within Subscribe.

  • Ola Eduardo, sorry is that I’m new in web development, and in case I leave the object in this case the this.empesa with value for all scope as it would be?

  • The properties of a component have the scope of the component. The way you did this, company will get the value of http return when this request is successful.

  • To see the value of your answer you can do so: this.empresaService.getEmpresa(empresaId). subscribe(Resp =>console.log(Resp))

1 answer

4

This is normal dude, it happens because the request you are making is asynchronous. If you want to give a 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);
    })
  }

That way when the request you made to the server is resolved the subscribe will run and the console.log will work..

Browser other questions tagged

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