How to return data as Promise type in Angular 2?
Using this function I need to return data as promise type:
private getStudyPeriods(): Promise<CurrentPeriod> {
let data = [];
return data;// here
}
I tried last variant like this:
public getStudyPeriods(): Promise<Period[]> {
return this.education.get(7).then((data: any) => {
if (!data.hasOwnProperty('errors')) {
this.periods = data;
return new Promise((resolve, reject) => {
resolve(this.periods);
});
}
})
}
resolve() method in JS returns a Promise object that is resolved with a given value. Any of the three things can happened: If the value is a promise then promise is returned. If the value has a “then” attached to the promise, then the returned promise will follow that “then” to till the final state.
What Is Promise in Angular? Promises in Angular provide an easy way to execute asynchronous functions that use callbacks, while emitting and completing (resolving or rejecting) one value at a time. When using an Angular Promise, you are enabled to emit a single event from the API.
To access the value of a promise in TypeScript, call the then() method on the promise, e.g. p. then(value => console. log(value)) . The then() method takes a function, which is passed the resolved value as a parameter.
Promise accepts a callback function as parameters, and in turn, the callback function accepts two other parameters, resolve and reject. If the condition is true, then resolve is returned; else, returns reject. Basically, the return type of Promise type is defined immediately after the keyword Promise.
Just return a Promise
the resolves itself immediately.
private getStudyPeriods(): Promise<CurrentPeriod> {
let data = [];
return new Promise(resolve => {
resolve(data);
});
}
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