1

I'd like to have a generic http get service I did it using the following code:

public get(module: String): Promise<any> { 
return this.http.get(module)
           .toPromise()
           .then(response => response.json().data as Any[])
           .catch(this.handleError);}

The problem is that now I'd like to know when the http.get is finished to fire a command and I don't know how to do it.

If I add something to the .then step it doesn't work

.then(response => response.json().data as Any[] && alert("HI"))

If I add a .then after the other then, it fires before the http request is fulfilled.

How can I achieve it?

Using dfsq code I'm able to fire alert("HI") but response is undefined. This is the way I use it:

this.dataService.get("myurl").then(response => console.log(response));

I get undefined

2
  • "If I add a .then after the other then, it fires before the http request is fulfilled." can you show this code? that is not how promise chaining works Commented Apr 18, 2017 at 14:36
  • @suraj I guess it's then(alert("Hi")). Commented Apr 18, 2017 at 14:38

1 Answer 1

1

You indeed need to add one more then block:

public get(module: String): Promise<any> { 
  return this.http.get(module)
           .toPromise()
           .then(response => response.json().data as Any[])
           .then(data => {
             alert("HI") // <---- do something here
             return data
           })
           .catch(this.handleError);
}

Make sure you return previous data from then block so you pass it further down promise chain.

Sign up to request clarification or add additional context in comments.

3 Comments

Sorry dfsq, the alert("HI") is working but now the response is not working. Why is that? I get undefined from console.log
response inside the get function returns the response. But outside the function returns undefined.
Where do you put console.log exactly?

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.