Return promise value in Angular 2, Ionic 2

I get acquainted with Angular2, Ionic2 and maybe I misunderstand something, but I was hoping for help.

I have a provider called "CurrentUser" to store and retrieve LocalStorage data.

getProfile(): any { this.local.get("user-profile").then((profile) => { var val = JSON.parse(profile); return val; }); } 

this getProfile() function returns a promise

If I introduce this provider into the component. How will I wait for the promise to resolve before assigning 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 } } 
+7
promise angular typescript ionic2
source share
2 answers

First of all, you should return this.local.get("user-profile") promise from the getProfile function getProfile that it can be a chain when called. After that, you can get the data returned from the getProfile function in the .then callback.

 getProfile(): any { return this.local.get("user-profile").then((profile) => { var val = JSON.parse(profile); return val; }); ); 

In addition, you cannot receive data as soon as you do ajax, if it is executed successfully, you can get an answer

 ngOnInit(): any { this._currentUser.getProfile().then( value => { console.log(value) } ) } 
+9
source share

Your getProfile function does not return a promise. It does not return anything. You have to 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 data from your promise variable.

  ngOnInit(): any { this._currentUser.getProfile().then(value => { console.log(value); //returns your value. } 
0
source share

All Articles