an Observer within an observable function is not feeding variable

Asked

Viewed 30 times

-2

what am I doing wrong? the variable test is not being fed, always Undefined

result.data is ok, the api is working and the query tbm, the problem is the variable test that always this Undefined

Angular+Apollo-graphql

getUser(data: String): Observable<any> {
      let test: any
      this.apollo.query({ query: gql`${data}` }).subscribe(result => {
         test = result.data
      })
      console.log(test)//<< sempre retorna undefined
      return test
   }
  • what I’m doing wrong? Just look at the sequence that Javascript runs and know what it is assíncrono!

1 answer

0

Hello, all right?

You are registering in the console the value of the variable test before the API response is received.

The code that is within the function you provided for the method subscribe will only be executed when a response is received by the API, but the code that is outside this function (even if below) will continue running in sequence.

In short: your call to console.log(test) happens before its assignment test = result.data.

You may find this MDN link on asynchronous programming useful: https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Asynchronous/Concepts.

Browser other questions tagged

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