Reputation: 1459
I am trying to use rxJS to handle responses from an http request in angular2
this is the code:
isUserConfirmed(): boolean {
let result: boolean = false;
this.authService.isUserConfirmed().subscribe(
retrievedData => {
//if no errors from the server
if (retrievedData.success) {
//if the confirmed flag is true
if (retrievedData.payload){
result = true;
console.log("i"+result);
} else {
result = false;
}
} else {
this.showError(retrievedData.message);
}
},
error => {
this.showError(error);
});
console.log("o"+result);
return result;
},
showError(error) {
//...
}
EDIT
When I run this, I get this output:
ofalse
itrue
This means that the result value is set to true inside suscribe method, but that does not change returned result value.
How can I manage to return the value set from inside the subscribe block?
Upvotes: 1
Views: 1456
Reputation: 29775
Its because your console statement outside the subscribe block will execute first. So your first console.log() will display false. Following your console.log() inside the subscribe block will be executed second. So it will result to true if success.
If Observable returns true, result should be :
false
true
You can return value in this way
isUserConfirmed(): boolean {
let result: boolean = false;
return this.authService.isUserConfirmed().subscribe(
retrievedData => {
//if no errors from the server
if (retrievedData.success) {
//if the confirmed flag is true
if (retrievedData.payload){
result = true;
console.log("i"+result);
}
} else {
this.showError(retrievedData.message);
}
return result
},
error => {
this.showError(error);
});
}
Upvotes: 1