【问题标题】:How to retrieve value from Storage and user it somewhere else in Ionic 2如何从存储中检索值并在 Ionic 2 的其他地方使用它
【发布时间】:2017-02-09 21:18:05
【问题描述】:

我是 Ionic 2 和 Promises 的新手,遇到了一些问题。

我的 Ionic 2 应用程序将 auth_token 保存到本地存储:

this.storage.set('auth_token', auth_token);

稍后在我的安全组件中,我想检查是否设置了令牌,但我不知道该怎么做。

我试过了:

authenticate() {
    var auth_token = this.storage.get('auth_token').then((val) => {
        return val;
    });
  }

然后我从其他地方打电话:

console.log(this.auth.authenticate);

但它不起作用,它只是返回函数本身。

如何从我的身份验证方法返回令牌?

【问题讨论】:

    标签: ionic-framework local-storage ionic2


    【解决方案1】:

    检查 here 以获取承诺链。

    在您的 authenticate() 函数中返回原始的承诺调用,然后在其他位置的函数中使用

    authenticate() {
        return this.storage.get('auth_token').then((val) => {
           return val;
        });
      }
    

    进行身份验证时...

    this.auth.authenticate().then((val)=>{
      console.log(val);
     }).catch(error=>{
       //handle error
     });
    

    【讨论】:

    • 谢谢!我可以以某种方式将各个部分组合在一起,以便在我的组件中我只需要调用 this.auth.getToken() 来获取令牌吗?
    • authenticate() 将在您的身份验证提供程序中。您可以在组件中注入身份验证并获取我在答案中输入的值
    【解决方案2】:

    您只是想检查还是需要退货?

    如果只是检查,你可以这样做:

    authenticate() {
      this.storage.get('auth_token').then((val) => {
       if(val){ ... } // or console.log it if it's just what you need.
      }
    }
    

    如果你需要返回,创建一个这样的承诺:

    authenticate = (): Promise<{exists: boolean, auth: any}> =>{
      return new Promise<{exists: boolean, auth: any}>(res =>{
        this.storage.get('auth_token').then((val) => {
          if(val){
            res({exists: true, auth: val});
          } else {
            res({exists: false, auth: val});
          }
        }
      })
    }
    

    之后调用authenticate().then(res =&gt;{}),访问res中返回的对象。

    编辑

    正如 Suraj 所评论和现在测试的那样,它不需要被封装在一个新的 Promise 中,所以如果你需要返回它,只需使用 Suraj 建议的方法。

    【讨论】:

    • 只是好奇..真的需要封装一个新的promise吗?
    • 如果他想使用带有承诺的 authenticate() 方法,我相信他需要这样做。从未测试过您使用的方法,现在将这样做,看看它是否更好。至少它更干净
    猜你喜欢
    • 2021-12-14
    • 1970-01-01
    • 2017-07-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-03-31
    相关资源
    最近更新 更多