Sunday, May 12, 2024
 Popular · Latest · Hot · Upcoming
12
rated 0 times [  13] [ 1]  / answers: 1 / hits: 53050  / 9 Years ago, fri, october 23, 2015, 12:00:00

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>();
this.http.get(MY_URL)
.map(res => res.json())
.subscribe(
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..


More From » angular

 Answers
65

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.


[#64629] Wednesday, October 21, 2015, 9 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
tylerdamiena

Total Points: 139
Total Questions: 90
Total Answers: 118

Location: Liechtenstein
Member since Wed, Dec 8, 2021
2 Years ago
tylerdamiena questions
;