Handle data collected through a JSON api

Asked

Viewed 276 times

-1

I am collecting data provided by a JSON API.

With the code below I can see that the data was collected within the Subscribe.

But outside it, inside the file itself . TS I cannot manipulate this data.

I tried to use the Promise, but I don’t think I used it correctly, because I didn’t get a positive result either.

How I could handle this data before presenting on screen?

getHour() {
this.hourService.getData()
  .subscribe(
    posts => this.posts = posts,
    error => this.errorMessage = <any>error,
  () => console.log(this.posts));     

  console.log(this.posts);
}

inserir a descrição da imagem aqui

  • You can put the return of this console.log?

  • Yes, I’ve already added

  • Opa they are only available within the same subscribe. That pq the http and asynchronous call.

  • I understood, and for me to use this data outside of subscribe I would need to use an async or await?

  • Rxjs and observables and other different form of async await to deal with asynchronizity.

  • but if it is inside the subscribe, why not change the data, since it was received correctly? or Oce uses the suggestion of @Eduardovargas

  • @Fsi Eduardo explained further below. I was already finding what he said tbm.

Show 2 more comments

2 answers

0

Think like this, dude, when you do hourService.getData an http request and fires when it is completed the Code inside the subscribe and runs(if that’s okay with the request)

 getHour() {
    this.hourService.getData()
      .subscribe( //http disparado
        posts => this.posts = posts, //quando a requisição terminou e deu certo
        error => this.errorMessage = <any>error,//quando a requisição terminou e deu errado
      );     

      console.log(this.posts);//aqui o http ainda não terminou por isso o undefined
}
  • Thank you, that’s exactly what I learned about it. I am using a Promise to use the data after they have been collected and assigned within the subscribe.

-1

You can save this return within a global variable.

var posts = this.posts;
  • Wow, nice, but the variable is always empty at runtime. I try to use the data in another function or even use this variable to then display it on the screen, and it is always empty.

  • declares the variable outside the function, within a global scope and within the function only assigns the value to it.

Browser other questions tagged

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