-1

I faced with difficulties for getting values from async queries using Observable in Angular 5

export class CustomComponent {
private external: any;

constructor(private http: HttpClient) {}

getContent() {
     return this.http.get('api/conten/get');
}


retrieve() {
    this.getContent().subscribe(content => {
        this.external = content;
        console.log(this.external) // here we get content that we expect
    });

    console.log(this.external); // there is 'undefined'
}

}

How can I set external variable with result from getContent()? Probably there are other ways?
I guess this situation very frequent when we need to use response in code bellow
Please, give example how can I get value from response immediately after request(e.g. make request sync within the framework of Angular)

  • Code inside subscribe it's called asynchronously. So when you call `console.log(this.external)` the code in subscribe has not yet been executed, hence the value of this.external is still undefined. – Ignasi Jun 13 '18 at 15:20
  • 1
    Possible duplicate of [How do I return the response from an Observable/http/async call in angular2?](https://stackoverflow.com/questions/43055706/how-do-i-return-the-response-from-an-observable-http-async-call-in-angular2) – ConnorsFan Jun 13 '18 at 15:27
  • Unfortunately this does not explain how to get the value immediately below the code – Nikita Chubukov Jun 13 '18 at 16:10

1 Answers1

1

The way you are doing things is correct.

The reason your second console.log prints undefined is simply because the retrieve function does not wait for your async operation (getContent()) to finish before moving on to the next line.

Here's a simplified timeline:

  1. Execute retrieve
  2. Execute getContent, oh, it's async, let's subscribe to it and move on
  3. Print this.externalundefined
  4. When getContent returns (sometimes later), assign the returned value to this.external
  5. Print this.externalcorrect value
bugs
  • 14,631
  • 5
  • 48
  • 52
  • Thank you a lot for answer. Perhaps there is a way to get value from **getContent()** immediately after **.subscribe()** for using the **this.external** variable below the code? – Nikita Chubukov Jun 13 '18 at 15:30