angular - 在函数完成使用 Angular 和 Ionic 之前,Promise 已成功解决
问题描述
我创建了一个服务,该服务具有从 API 检索令牌的方法,该 API 在内部调用 subscribe()。此方法从组件调用,不返回 Observable,只返回包含令牌的字符串。
然后,在获取令牌后,应该从组件调用另一种方法,但是,它总是在另一个方法之前被调用。我什至尝试过在组件中使用 async/await,但它没有用。
// api.service.ts
logIn() {
if(!this.token) {
this.http.post(this.apiURL + "/token/", {username: "test", password: "test"}, options).subscribe(response => {
if(response.status == 200) {
this.body = response.body;
this.token = "Token " + this.body.token;
window.sessionStorage.setItem("TOKEN_KEY", this.token);
console.log(this.token);
}
}
return this.token;
}
如您所见,该方法只返回令牌,因此我在组件中创建了一个 Promise,一旦解决了调用 getProduct() 方法,但它在令牌已经存在之前被调用。
// product.component.ts
async getLogin() {
const resp = await this.apiService.logIn();
console.log(resp);
}
getMenu() {
this.apiService.getMenu().subscribe(resp => {
console.log(resp);
});
constructor(private apiService: APIService) {
this.getLogin().then(resp => {
console.log('Called');
// Call before the token has already been created!
this.getMenu();
});
}
解决方案
问题是您的函数在异步调用中logIn
设置了值,因此当您尚未分配它时。你要早点回来。如果你想使用Promise方法,那么必须返回一个Promisethis.token
this.http.post
return this.token;
logIn
async logIn() {
if(!this.token) {
return this.http.post(this.apiURL + "/token/", {username: "test", password: "test"}, options)
.toPromise()
.then(response => {
if(response.status == 200) {
this.body = response.body;
this.token = "Token " + this.body.token;
window.sessionStorage.setItem("TOKEN_KEY", this.token);
console.log(this.token);
return this.token; // important to return the token here
}
}
}
return this.token;
}
请注意,我已将async
关键字添加到logIn
函数中,更改了subscribe
for toPromise
,链接.then
并添加return this.token
到其中。
希望能帮助到你。
推荐阅读
- github - 在 github 工作流中使用 github 组织机密
- database - 带有列名的列?
- python - 如何将 html 和 css 添加到我的 kivy 应用程序项目中?
- python - Django 在 Windows Server 上使用 mod_wsgi。没有名为“lxml.etree”的模块
- python - Python CSV to JSON 引用嵌套对象
- javascript - 如何使用递归函数获取分页的 json 数据
- java - HTTPS 上的 SpringBoot Zuul 网关
- powershell - 如何使用 Powershell 修改 Firefox 配置(pref.js)
- python - 具有特定值的 for 循环中的熊猫数据框
- javascript - 将自定义 ACE 编辑器模式导入 Brace 时,需要调用找不到帮助模块