Returning a promise value in Angular 2, Ionic 2
16,446
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) }
)
}
Author by
Arianule
Updated on July 10, 2022Comments
-
Arianule almost 2 years
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 promiseIf 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 } }