How can I check if a service is completed then run rest of the code?
example:
I want to get some data from API like this:
get_user_info(token: string): Observable<any> {
return this.http.get(this.home + 'api/home/account/excerpt?token=' + token)
.map((response: Response) => {
return response.json().result;
});
}
and I want to subscribe the data from get_user_info
:
retrieve_user_info() {
this.http.get_user_info(this.back_result.token).subscribe(
(result: sendBackUserInfo) => {
if (result.result == 1) {
this.user_info = result.user;
} else {
console.log(result.messages[0]);
}
}
);
}
but the problem is when I call the function retrieve_user_info
, it doesn't get data immediately.
how can I fix that?
EDIT:
this is how I call retrieve_user_info
:
submit_login_form() {
this.http.login_user(this.username, this.password, this.result.language.code)
.subscribe((result: loginSendBackResult) => {
this.back_result = result;
this.retrieve_user_info();
if (this.back_result.result == 1) {
this.show_modal = false;
console.log(user_info);
router.navigate(['home']);
}
});
}
You can use flatMap
to chain your requests. Also your naming made me a bit confused. When referring to service method, I would name the service something like service
instead of http
to separate where we are making a http-request and where we are calling a method in the service. So I used service
here on those places instead.
import "rxjs/add/operator/mergeMap";
submit_login_form() {
this.service.login_user(...)
.flatMap((result: loginSendBackResult) => {
this.back_result = result;
return this.retrieve_user_info();
});
.subscribe(data => {
if(this.back_result.result == 1) {
console.log(this.user_info)
....
}
})
}
and your retrieve_user_info()
retrieve_user_info() {
return this.service.get_user_info(this.back_result.token)
.map((result: sendBackUserInfo) => {
if (result.result == 1) {
return this.user_info = result.user;
} else {
console.log(result.messages[0]);
}
});
}