【发布时间】:2019-03-12 18:27:49
【问题描述】:
请原谅 noobie 错误,我正在尝试来自 C# 背景的 Ionic,因此这可能是问题的一部分。 我正在尝试从 Ionic 存储中获取存储的令牌,但我很难理解承诺,因此决定使用“等待”,因为我在 c# 中已经习惯了。
这是我要构建的 Api 服务的一部分,因此需要按顺序获取我的 http 标头,因此在构造函数中我检索令牌以将其添加。 下面是一段Api服务TS文件:
export class ApiService {
ServerUrl = environment.url;
BearerToken: string;
GetUserDetailsEndPoint = 'api/Account/GetUserDetails';
UpdateUserDetailEndPoint = 'api/Account/UpdateUserDetail';
TokenEndPoint = 'Token';
RegisterEndPoint = 'api/Account/Register';
httpOptions = {
headers: new HttpHeaders({
'Content-Type': 'application/json',
'Authorization': 'bearer ' + this.BearerToken
})
};
constructor( private http: HttpClient,
private storage: Storage,
private alertController: AlertController ) {
this.getBearerToken(); // I put this in a function cos not sure how the async stuff plays out in a constructor
console.log('Have awaited the token and its value is:' + this.BearerToken);
}
async getBearerToken() {
this.BearerToken = await this.storage.get(TOKEN_KEY);
}
很简单,“this.BearerToken”在发送到控制台时是未定义的。 (该值确实存在于商店中)。 它显然是某种异步类型的问题,但我很难理解为什么“等待”没有..? 我已经阅读了很多,但大多数时候人们都在使用带有 promise 的 .then 功能。我在这里想念什么? 谢谢
编辑 在这里听取了 Igor 的建议后,我将初始化从 UserService 移到了我的菜单页面的 ngOnInit 中,这是我首先需要使用它的地方。我在从本地存储而不是令牌获取用户信息的同一领域内,但这是同一个问题。 所以我想我仍然无法理解一些东西......获取存储用户的功能是这样的:
async getUserStore() { // Populate the data object with the stored info
this.data = await this.storage.get(USER_DATA);
console.log('getUserStore: email = ' + this.data.Email);
}
其中 this.data 是服务类中的 UserData 对象。 然而,这个函数仍然返回一个promise,而不是在返回之前等待。我是否需要让它返回一些特定的东西才能让 await 真正等待?例如
return await this.storage.get(USER_DATA);
或使用 .then 方法,如果是,那么“等待”它的意义何在?
我的调用函数如下所示:(按预期工作)
ngOnInit() {
this.user.getUserStore().then(() => {
console.log('ngOnInit - menu page, this.user email is: ' + this.user.data.Email);
if (this.user.data && !this.user.data.DetailsComplete) {
this.showAlert('Your Details are incomplete, please can you complete them?');
}
console.log('ngOnInit - menu page');
});
}
而异步函数中的 await 我希望它看起来像这样:(这不起作用)
ngOnInit() {
this.user.getUserStore();
console.log('ngOnInit - menu page, this.user email is: ' + this.user.data.Email);
if (this.user.data && !this.user.data.DetailsComplete) {
this.showAlert('Your Details are incomplete, please can you complete them?');
}
console.log('ngOnInit - menu page');
}
那么我如何(使用等待)让它在被调用函数中真正等待?还是不能? 干杯
【问题讨论】:
-
你没有在构造函数中等待调用
this.getBearerToken();。出于其他原因,您不应该在构造函数中执行异步操作,但这就是尚未完成的原因。
标签: angular typescript ionic-framework