Reputation: 9063
I am familiarizing myself with Angular2, Ionic2 and maybe I am misunderstanding something but was hoping for assistance.
I have a provider called 'CurrentUser' for the purpose of storing and getting LocalStorage data.
getProfile(): any {
this.local.get("user-profile").then((profile) => {
var val = JSON.parse(profile);
return val;
});
}
this function getProfile()
returns a promise
If I inject this provider into a component. How would I await the promise to to resolve before assigning the data when calling this function from the component?.
@Component({
templateUrl: 'build/pages/book_meeting/book_meeting.html'
})
export class BookMeetingPage implements OnInit {
constructor(public navCtrl: NavController, private _currentUser: CurrentUser) {
}
profile: IProfile;
ngOnInit(): any {
this.profile = this._currentUser.getProfile();
console.log(this.profile);//returns undefined
}
}
Upvotes: 7
Views: 16465
Reputation: 136184
First of all you have to return this.local.get("user-profile")
promise from getProfile
function so that it can chain when you call. Thereafter you can get data returned from getProfile
function in .then
success callback.
getProfile(): any {
return this.local.get("user-profile").then((profile) => {
var val = JSON.parse(profile);
return val;
});
);
Additionally you can't get data as soon as you make an ajax, on success of it you can get the response
ngOnInit(): any {
this._currentUser.getProfile().then(
value => { console.log(value) }
)
}
Upvotes: 9
Reputation: 769
Your function getProfile doesn't return a promise. It returns nothing. You should change it to
getProfile(): any {
return this.local.get("user-profile").then((profile) => {
var val = JSON.parse(profile);
return val;
});
Now in your component, you can extract the data from your profile promise variable.
ngOnInit(): any {
this._currentUser.getProfile().then(value => {
console.log(value); //returns your value.
}
Upvotes: 0