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
}
}
Angular – Promise Explained with Code Example. Promise, in Javascript, is a concept which allows the callee function to send back a promise (sort of assurance) to the caller function that it would, for sure, send back a resolution, be it a success or a failure at a little later point of time.
Since Ionic is now using TypeScript 2.2.1 at the time of writing this, we are able to make use of Async/Await in our Ionic applications. In this tutorial, I am going to show you exactly how you can use Async/Await with promises in an Ionic application, and compare it to the "normal" syntax.
The HttpClientModule is required to trigger HTTP calls from the Angular applications . Now, open the app.component.ts file, then we will add code to make HTTP Get API request and handle the response using the ECMAScript Promise in Angular. In the constructor, inject the HttpClient service.
Angular 11 Promises Example with HttpClient API. In this section, we are going to look at how to use Promises in Angular to manage the HTTP response asynchronously. Open your Angular project in your favorite code editor and then go to app.module.ts file and import HttpClientModule service. Then also register it inside the imports array.
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) }
)
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With