Currently working on developing a new APP using Ionic.
Here is the structure of a service I am using:
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";
@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);
});
console.log("UserId", this.userid);
}
use_storage_data() {
this.getFromStorageAsync();
console.log("Userid",this.userid);
let postData = {
userid: this.userid,
username: "samplename"
};
return this.http
.post<any>(this.serverUrl + "/appdata.php", postData)
.pipe(catchError(this.handleError));
}
}
When calling the service on a page, it is done like this:
getData(){
this.myservice.use_storage_data().subscribe(data => {
// console.log(data);
});
}
I am looking for help in making storage data a global variable or suggestions on a better approach to manage and utilize user id and user name data in an Ionic app.
NOTE: User id is successfully set when a user logs in.
Thank you.