离子存储:奇怪的行为?

Ionic Storage : Strange behavior?

我尝试使用 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';
  }

我尝试了很多东西,return 直接值,设置值和 return 变量... 但我总是得到一个 null,奇怪的是,如果我直接 return 一个字符串,它就可以工作,当我 console.log val 它显示的字符串我想要,但 return 始终为 null..

我做错了什么?

编辑:

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

/**
   * 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);

还是null

您正在从 storage.get() 方法中获得 Promise。 这意味着它是 运行 异步的。 你可以return答应。

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

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

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