I'm currently facing an issue, when the UserData is injected into my other component, the Load() function will always started earlier than the getFromStorageAsync() within the constructor, so ip_address is always undefined.
the below is my service code (UserData)
import { Injectable } from '@angular/core';
import { Http } from '@angular/http';
import { Storage } from '@ionic/storage';
import 'rxjs/add/operator/map';
/*
Generated class for the UserData provider.
See https://angular.io/docs/ts/latest/guide/dependency-injection.html
for more info on providers and Angular 2 DI.
*/
@Injectable()
export class UserData {
public data: any;
private ip_address: any;
constructor(public http: Http, private storage: Storage) {
this.data = null;
this.ip_address = this.getFromStorageAsync()
}
async getFromStorageAsync(){
let val = await this.storage.get('ip_address');
this.ip_address = val.toPromise();
}
load(): any {
console.log(this.ip_address);
if (this.data) {
return Promise.resolve(this.data);
}
return new Promise(resolve => {
this.http.get(this.ip_address + "/api/user")
.map(res => res.json())
.subscribe(data => {
this.data = data;
resolve(this.data);
});
});
}
}
it failed to fetch data from server due to undefined ip address. is it correct way to use async and await. please help. thanks !
load()method?