【问题标题】:Waiting in Ionic 2 typescript for local storage promise to resolve before continuing在 Ionic 2 打字稿中等待本地存储承诺在继续之前解决
【发布时间】:2017-05-31 13:28:33
【问题描述】:

我有一个 Ionic 2 应用程序,我想在其中实现注销功能。我想在本地存储中将 Json Web Token 的值设置为 null,然后在设置值后,将用户发送到登录页面。

我遇到了一个问题,即应用程序在将用户带到登录页面之前没有等待设置 JWT 的值。这是一个问题,因为在登录页面上,如果用户有有效的 JWT,我有一个自动登录的功能。因为程序没有阻塞并等待在存储中设置值,所以用户在注销后立即重新登录。

在将用户发送回登录页面之前,如何等待设置令牌的值?

注销功能:

logout() {
this.storage.ready().then(() => {
    this.storage.set('token', '').then(data => {
        this.navCtrl.setRoot(LoginPage);
    });
});

CheckAuthentication 功能:

    checkAuthentication() {
return new Promise((resolve, reject) => {
  this.storage.get('token').then((value) => {

    this.token = value;

    let headers = new Headers();
    headers.append('Authorization', this.token);

    this.http.get('apiURL', { headers: headers })
      .subscribe(res => {
        resolve(res);

      }, (err) => {
        reject(err);
      });

  });

  });
  }

IonViewWillLoad:

  ionViewWillLoad(){
 //Check if already authenticated
    this.auth.checkAuthentication().then((res) => {
        console.log("Already authorized");
        this.loading.dismiss();
        this.navCtrl.setRoot(HomePage);
    }, (err) => {
        console.log("Not already authorized");
        this.loading.dismiss();
    });}

【问题讨论】:

    标签: angular typescript promise ionic2 json-web-token


    【解决方案1】:

    您可以在这里做一些事情。

    首先,我会重构代码以使其更具可读性。如果您了解我如何拥有以下功能,您会注意到我们正在利用 Promise 自然赋予我们的优势,因为我们可以将它们链接在一起,而无需嵌套我们的 then()s。

    checkAuthentication() 中,您不需要像以前那样创建 Promise。您可以将 http Observable 作为承诺返回。如果 http 调用成功,则 promise 将解决。如果 http 调用失败,则生成的 Promise 将拒绝。

    最后,我会尝试使用ionViewDidLoad 而不是willLoad

    logout() {
      this.storage.ready()
        .then(() => this.storage.set('token', ''))
        .then(data => this.navCtrl.setRoot(LoginPage))
    }
    
    checkAuthentication() {
      return this.storage.get('token')
        .then((value) => {
          this.token = value;
    
          let headers = new Headers();
          headers.append('Authorization', this.token);
    
          return Observable.toPromise(
            this.http.get('apiURL', { headers: headers })
          );
        });
    }
    
    ionViewDidLoad() {
      this.auth.checkAuthentication()
        .then((res) => {
          console.log("Already authorized");
          this.loading.dismiss();
          this.navCtrl.setRoot(HomePage);
        })
        .catch((err) => {
          console.log("Not already authorized");
          this.loading.dismiss();
        });
    }

    【讨论】:

    • 该问题与我在此处发布的代码无关。单击注销按钮时,我实现的注销功能未运行。这是因为我编辑了错误的 typecipt 文件。不过,感谢您的重构建议。
    【解决方案2】:

    在注销功能中,它应该删除令牌而不是将其设置为空''。因为注销后token还在存储中。

    this.storage.removeItem('token')
    

    【讨论】:

      猜你喜欢
      • 2018-12-14
      • 2017-07-31
      • 2018-09-29
      • 1970-01-01
      • 2021-08-11
      • 2018-10-02
      • 1970-01-01
      • 2017-03-11
      相关资源
      最近更新 更多