0

In my app, I'm calling a service :

getEnv(): Promise<string>{
        return this.http.get(this.url + 'Home/GetEnv')
        .toPromise()
        .then(response => response.json().environment)
        .catch(this.handleError);
    }

to return to a component

getEnvironnement(): string {

      this.appService.getEnv().then(url => {
          this.url = url;
      })  

      return this.url;
  }

The problem is the following. When I'm calling MyComponent.getEnvironnement(), the result is undefined, because the call to my service is async, I know all this stuff. But.. Is there a way to wait before returning this.url ?

Thanks !

Alex Caron
  • 350
  • 3
  • 19
  • 2
    If you wait for this operation, for example it takes 2 minutes to complete the http request, what would your user be doing in this time period? There's a reason why we have async operations in front-end world, you should embrace it. – eko Jul 07 '17 at 13:21
  • Ok. So how can I return this.url ? – Alex Caron Jul 07 '17 at 13:23
  • You don't/can't. You set the field `url` on the component, that's it. – Igor Jul 07 '17 at 13:23
  • Where are you going to use it? – eko Jul 07 '17 at 13:23
  • @AlexCaron Small note tangential to the question. You probably shouldn't be both setting `this.url` and returning it in the same function, although I don't know enough about your code to understand what you're doing. In general, mutating things in asynchronous code is a recipe for a difficult to understand program. – Asad Saeeduddin Jul 07 '17 at 13:30
  • 3
    Possible duplicate of [How do I return the response from an asynchronous call?](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – Estus Flask Jul 07 '17 at 13:39

1 Answers1

1

You can use async-await to write your code in a sequential style, while still retaining the benefits of non-blocking async HTTP requests:

async getEnvironnement(): Promise<string> {
  this.url = await this.appService.getEnv();
  return this.url;
}
Asad Saeeduddin
  • 46,193
  • 6
  • 90
  • 139