0

I am trying to do HTTP get/post request. Even with a fresh install of Angular 4 using the CLI, I am facing an unusual problem. When I send get request for first attempt then it gives undefined on console.log(), though from 2nd attempt data shows normally. Same result on Laravel as a server and even on JSON file. But while printing fetched data it prints but after few seconds. But it is OK though.

Same kind of problem arises on post request as well. Whenever form submits nothing happens on first attempt and shows some error on console.log() that server is not connected (something like that), and on second attempt it just submits normally as it should be.

this.http.get(path).subscribe(data => this.response = data);
this.http.post(path, formData).subscribe(data => this.response = data);
jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
Suson Waiba
  • 156
  • 1
  • 2
  • 9
  • There is nothing obviously wrong in what you've done, although if you're expecting `this.response` to be immediately available you haven't understood that this happens *asynchronously*. Please give a [mcve] that provides some usable context. – jonrsharpe Jun 11 '17 at 09:37
  • Without having more information, I believe though that this is the issue... https://stackoverflow.com/questions/43055706/how-do-i-return-the-response-from-an-observable-http-async-call-in-angular2 – AT82 Jun 11 '17 at 09:50

1 Answers1

0

thanks for response! I got it.! whatever we need to do with return data from http should be

this.http.post(path, formData).subscribe(
data => {
this.response = data,
//should be here <<--
}
);

anything after this code will not wait for http response to complete, instead get triggered instantly.

Suson Waiba
  • 156
  • 1
  • 2
  • 9