Navin Navin - 5 days ago 5x
AngularJS Question

How to synchronise Angular2 http get

I understand using observable I can execute a method when the request is completed, but how can i wait till a http get is completed and return the response using in ng2 http?

getAllUser(): Array<UserDTO> {

this.value = new Array<UserDTO>();
.map(res => res.json())
data => this.value = data,
err => console.log(err),
() => console.log("Completed")

return this.value;

the "value" will is null when its returned because get is async..


You should not try to make http calls behave synchronously. Never a good idea.

Coming to your getAllUser implementation it should return an observable from the function and the calling code should subscribe instead of you creating a subscription inside the method itself.

Something like

getAllUser(): Observable<UserDTO> {
        return this.http.get("MY_URL")
                        .map(res => res.json());

In you calling code, you should subscribe and do whatever you want.