angular - 在其他功能上使用离子存储数据
问题描述
我正在使用离子开发一个新的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
问候。
解决方案
您正在处理 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));
});
}
}
希望有帮助
推荐阅读
- c++ - 如何从 exe 中读取内存地址的值?
- c# - 在 WPF 应用程序中支持 Windows 11 对齐布局
- cypress - 在 Cypress.io 测试中两次调用钩子之前
- firefox - 如何在 Firefox 中注销 Shared Worker
- f# - 如何将 F# 结果类型列表拆分为内部类型列表
- python - Keras 输入 Pandas 数据框
- c# - 将 prometheus 静态标签添加到公共交通指标
- html - 移动/缩放 HTML 元素会在整个地方留下边框残留物
- asp.net - 从 NET4.8 迁移到 NET5/Core,是否需要 Full Framework?
- python - 如何从嵌套的字典键和值列表中创建多索引数据框?