angular - 角嵌套订阅调用
问题描述
我有一个Ionic
应用程序并尝试使用and来实现Login
此模块。PHP REST
JWT
1) 用户输入凭证和 api 返回token
2)将令牌存储在capacitor
存储中并拦截下一个http
请求并在标头中添加令牌
3)回调api并获取登录用户信息
4)将信息存储在capacitor
存储中并继续进行。
以下是代码。
loginAction() {
if (this.validateInputs()) {
console.log(this.postData);
this.authService.login(this.postData).subscribe(
(res: any) => {
console.log(res);
if (res.token) {
this.storageService.store('accessToken', res.token);
this.authService.getUserProfile().subscribe((profile: any) => {
console.log(profile);
this.storageService
.store(AuthConstants.AUTH, profile)
.then(res => {
this.router.navigate(['home']);
});
});
}
},
(error: any) => {
this.toastService.presentToast('Network Issue.');
}
);
} else {
this.toastService.presentToast(
'Please enter email/username or password.'
);
}
}
我遇到的唯一问题是capacitor
嵌套订阅调用。
有时执行获取 的profile
速度很快,并且拦截返回的值为accessToken
.
如何确保仅在正确存储http
后才执行第二次调用?accessToken
export class StorageService {
constructor() {}
// Store the value
async store(storageKey: string, value: any) {
const encryptedValue = btoa(escape(JSON.stringify(value)));
await Storage.set({
key: storageKey,
value: encryptedValue
});
}
}
谢谢
解决方案
编辑storageService.store()
函数以返回Storage.set
. 根据文档,它返回一个 Promise。然后,您可以申请.then
您的电话并在回调中处理您的操作。
export class StorageService {
constructor() { }
// Store the value
public store(storageKey: string, value: any): any {
const encryptedValue = btoa(escape(JSON.stringify(value)));
return Storage.set({ key: storageKey, value: encryptedValue });
}
}
在你的 loginAction() 函数中:
if (res.token) {
this.storageService.store('accessToken', res.token).then(
data => {
this.authService.getUserProfile().subscribe((profile: any) => {
console.log(profile);
this.storageService
.store(AuthConstants.AUTH, profile)
.then(res => { this.router.navigate(['home']); });
});
},
error => { // handle error }
);
}
推荐阅读
- gradle - Gradle:在哪里可以找到一些关于 gradle 缓存目录的教程
- java - 它是 Selenium 文档中的错误吗?
- jquery - Jquery .find() 在表中返回未定义
- java - 您的 SQL 语法有错误:在第 1 行的 'ID="" 附近使用的语法
- tendermint - 在 aws ec2 实例中运行 Tendermint
- java - 如何使用条件注释覆盖spring中的配置(例如)
- angular - 将 Angular 应用程序部署到 Azure Web 应用程序 Angular 9 的问题
- c# - 验证 URL 时出现“请求被中止:无法创建 SSL/TLS 安全通道”异常
- php - 检查单选按钮是否具有正确的数据库值
- java - Apache Ignite 中客户端的内存指标