Reputation: 177
This post method is using in angular2. In this ajax call , the post method is doesnt waiting for response. can any one say how to use observable for holding the asynchrouous in javascript until response receives .
this.http.post("http://jsonplaceholder.typicode.com/posts",body,options)
.map((res:Response) => res.json())
.subscribe(
data => { console.log("data is",data)},
err => console.error(err),
() => console.log('done')
);
Upvotes: 2
Views: 85
Reputation: 3872
Lets say this is your code:
let myData = null;
this.http.post("http://jsonplaceholder.typicode.com/posts",body,options)
.map((res:Response) => res.json())
.subscribe(
data => {
myData = data;
console.log("data is",data);
},
err => console.error(err),
() => console.log('done')
);
console.log("Log the data again", myData);
So as you well know, the second logging will log null since the Observable probably hasn't retrieved a result yet. What you should do is simply put all the code that depends upon the data being ready inside the subscribe result handler, like so:
let myData = null;
this.http.post("http://jsonplaceholder.typicode.com/posts",body,options)
.map((res:Response) => res.json())
.subscribe(
data => {
myData = data;
console.log("data is",data);
console.log("Log the data again", myData); // <--
},
err => console.error(err),
() => console.log('done')
);
Upvotes: 0
Reputation: 657731
When the response arrives
data => { console.log("data is",data)},
is executed.
If you want other or more code to be executed when Data arrives, then add this code inside { }
(instead or in addition to console.log(...)
)
That's how async execution works and there is no other way.
Upvotes: 1