我有一个带有类和方法的角度2app,该方法执行web api调用然后在本地存储上设置一些项目,问题是因为它的ASYNC然后在下一行我没有本地存储值但是因为web api在那时没有返回任何信息。
如何确保在localstorage.getitem行之前成功返回了web api。
为简洁而减少了代码。
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('a@com.com');
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();
}
}
答案 0 :(得分:1)
为了确保您拥有正确的信息,您不应该在您的服务中订阅,而是在您的组件中订阅:
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('a@com.com').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();
}