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 !

6
  • 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. Commented Jul 7, 2017 at 13:21
  • Ok. So how can I return this.url ? Commented Jul 7, 2017 at 13:23
  • You don't/can't. You set the field url on the component, that's it. Commented Jul 7, 2017 at 13:23
  • Where are you going to use it? Commented Jul 7, 2017 at 13:23
  • 3
    Possible duplicate of How do I return the response from an asynchronous call? Commented Jul 7, 2017 at 13:39

1 Answer 1

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;
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.