Issue
Am using ionic to develop a new APP.
i have have a service lool like this
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));
}
}
Then on page i call it like this
getData(){
this.myservice.use_storage_data().subscribe(data => {
// console.log(data);
});
}
Please help me to make storage data as global variable Or you may suggest a new approach to save and use data like user id and user name on ionic app
NOTE i have successful set userid when user login
Regards.
Solution
I change the way i get value from storage
On page i import this
import { Storage } from "@ionic/storage";
Get value from storage and pass to service
getData(){
this.storage.get('userid').then((val)=>{
this.myservice.use_storage_data(val).subscribe(data => {
console.log(data);
});
});
}
This work perfectly
Answered By - EwS
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.