Reputation: 34008
I have an angular 2app with a class and a method, the method executes a web api call and then sets some items on local storage, the problem is that because its ASYNC then on the next line I dont have the local storage values yet because the web api hasnt returned any info at that point.
How can I make sure that the web api has been succesfully returned before the localstorage.getitem line.
Code reduced for brevity.
login(email) {
let params: URLSearchParams = new URLSearchParams();
params.set('email', email);
//Header
let headers = new Headers({
'Content-Type': AppSettings.ContentType,
'Authorization': AppSettings.Authorization + localStorage.getItem("AccessToken"),
'X-Developer-Id': AppSettings.XDeveloperId,
'X-Api-Key': AppSettings.XApiKey
});
var RequestOptions: RequestOptionsArgs = {
url: AppSettings.UrlLoginPatient,
method: 'GET',
search: params,
headers: headers,
body: null
};
this.http.get(AppSettings.UrlLoginPatient, RequestOptions)
.map(res => res.json())
.subscribe(
data => { this.saveData(data, email); },
err => this.Error(err)
);
}
saveData(data, email) {
localStorage.setItem('patientId', data.data.patientId);
localStorage.setItem('emailLogin', email);
}
Error(err) {
console.log('error: ' + err);
}
LoginApp() {
this.login.login('[email protected]');
if (localStorage.getItem("patientId") != null) {
this.navCtrl.push(AttentionTypePage);
} else {
let alert = this.alertCtrl.create({
subTitle: 'El correo electrónico no ha sido encontrado.',
buttons: ['Intentar nuevamente']
});
alert.present();
}
}
Upvotes: 0
Views: 342
Reputation: 21564
To ensure that you have the right informations, you shouldn't subscribe in your service but in your component :
login(email) {
//do stuff with headers, and request options
return this.http.get(AppSettings.UrlLoginPatient, RequestOptions)
.map(res => res.json())
.do(data => this.saveData(data, email));
}
LoginApp() {
this.login.login('[email protected]').do(data => {
if (localStorage.getItem("patientId") != null) {
this.navCtrl.push(AttentionTypePage);
} else {
let alert = this.alertCtrl.create({
subTitle: 'El correo electrónico no ha sido encontrado.',
buttons: ['Intentar nuevamente']
});
alert.present();
}
}).subscribe();
}
Upvotes: 1