首页 > 解决方案 > 角嵌套订阅调用

问题描述

我有一个Ionic应用程序并尝试使用and来实现Login此模块。PHP RESTJWT

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
    });
  }
}

谢谢

标签: angularionic-framework

解决方案


编辑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 }
  );
}

推荐阅读