【问题标题】:Ionic Storage : Strange behavior?离子存储:奇怪的行为?
【发布时间】:2019-05-07 21:47:55
【问题描述】:

我尝试使用 Ionic Storage 模块来存储一些值,例如我的身份验证令牌:

/**
   * Get Token
   */
  public get token(): string {
    this.storage.get(this.LS_TOKEN).then((val) => {
      console.log(val);
      this._token.next(val);
      console.log( this._token.getValue());
    });

    return this._token.getValue();
    // return 'testtttt';
  }

我尝试了多种东西,直接返回值,设置值并返回变量...... 但我总是得到一个null,奇怪的是,如果我直接返回一个字符串,它会起作用,当我console.log val 它显示我想要的字符串,但返回总是空的。 .

我做错了什么?

编辑:

作为对第一个答案的回应,我尝试了这个:

/**
   * Get Token
   */
  public get token() {
    this.tokenPromise().then(yourToken => {
      console.log(yourToken);
      return yourToken;
    });
  }

  public tokenPromise() {
    return new Promise((resolve, reject) => {
      this.storage.get(this.LS_TOKEN).then((val) => {
        resolve(val);
      }).catch(ex => {
        reject(ex);
      });
    });
  }

我的问题是一样的,在我尝试使用的组件中:console.log(this.sharedService.token);

它仍然是空的

【问题讨论】:

  • 请显示您的 storage.set 方法。

标签: ionic-framework ionic4


【解决方案1】:

它不适用于您的新 token() 方法。 它仍然是异步的。我会告诉你:

public get token() {
    return new Promise((resolve, reject)=>{
        this.storage.get(this.LS_TOKEN).then((val) => {
            resolve(val);
        }).catch(ex=>{
            reject(ex);
        });
    });
}

现在您可以像这样使用共享服务中的令牌:

this.sharedService.token.then(token=>{
    //use token here;
});

或者你可以使用await,但是调用它的函数必须是异步的:

async useTokenFromService(){
    let token = await this.sharedService.token;
    console.log(token);
}

【讨论】:

  • 问题是,在我的共享服务中,我有多个值,例如令牌,有时我需要获得 4-5 个值,为每个值和每个值创建一个 then 很烦人我需要的组件
  • @Jessydan 然后让你的方法异步获取所有 4-5 个值并使用 await 作为令牌,就像在我的上一个示例中一样
【解决方案2】:

你从 storage.get() 方法中得到了一个 Promise。 这意味着它正在异步运行。 你可以返回 Promise。

public get token() {
    return new Promise((resolve, reject)=>{
        this.storage.get(this.LS_TOKEN).then((val) => {
            resolve(val);
        }).catch(ex=>{
            reject(ex);
        });
    });
}

您可以通过异步函数接收它并等待结果:

async loadToken(){
   let loadedToken = await this.token();
   // use your loadedToken here...
}

或者你可以像这样使用 Promise 中的 .then 方法:

loadToken(){
    this.token().then(yourToken=>{
        // use the token yourToken here...
    });
}

【讨论】:

  • 这是否可以让一个函数直接返回令牌字符串?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-07-19
  • 2017-06-21
  • 2020-05-17
  • 2021-06-10
  • 2015-09-03
相关资源
最近更新 更多