首页 > 解决方案 > 在其他功能上使用离子存储数据

问题描述

我正在使用离子开发一个新的APP。

我有这样的服务大厅

import { Injectable } from "@angular/core";
import { HttpClient, HttpHeaders } from "@angular/common/http";
import { Observable, of } from "rxjs";
import { catchError, tap } from "rxjs/operators";
import { environment } from "src/environments/environment";
import { Storage } from "@ionic/storage";
//No problem on import

@Injectable({
  providedIn: "root"
})
export class myservice {

  serverUrl = environment.baseUrl;

  httpHeader = {
    headers: new HttpHeaders({ "Content-Type": "application/json" })
  };

  userid: number;

  constructor(private http: HttpClient, private storage: Storage) {
  }

  async getFromStorageAsync(){
      await this.storage.get('userid').then((val)=>{
        this.userid = val;
        console.log("UserId", this.userid); //Here it work fine
      });
      console.log("UserId", this.userid); // Here it work fine too
  }

  use_storage_data() {
    this.getFromStorageAsync();
    console.log("Userid",this.userid); // Here is undefined
    let postData = {
      userid: this.userid, // here is undefined
      username: "samplename"
    };
    return this.http
      .post<any>(this.serverUrl + "/appdata.php", postData)
      .pipe(catchError(this.handleError));
  }

}

然后在页面上我这样称呼它

  getData(){
    this.myservice.use_storage_data().subscribe(data => {
     // console.log(data);
    });
  }

请帮助我将存储数据作为全局变量或者您可以建议一种新方法来保存和使用 ionic 应用程序上的用户 ID 和用户名等数据

注意我在用户登录时成功设置了用户ID

问候。

标签: angulartypescriptionic-framework

解决方案


您正在处理 Future ,因此在第一次调用时, userId 是未定义的,因为该方法是异步的,即它在幕后运行,而其他进程继续进行......

userId 变量的值将在将来的某个地方更新,因此要在您的程序中解决这个问题,您必须在您的方法中添加一个 .then 东西,这样每当从异步方法获取值时,您的变量 userId 就会更新..

给你看代码....

use_storage_data() {
    this.getFromStorageAsync().then(val => console.log(val)); //here it will be defined
    // what you could do now:
    this.getFromStorageAsync().then((id){
      console.log("Userid", id); // defined
    if(id){
    // to ensure that the first undefined value(if any) of id is not captured
    let postData = {
      userid: this.userid, // here is undefined
      username: "samplename"
    };
    return this.http
      .post<any>(this.serverUrl + "/appdata.php", postData)
      .pipe(catchError(this.handleError));
    });
    }
    
  }

希望有帮助


推荐阅读