Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to return data as Promise type in Angular 2?

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);
        });

      }
    })
  }
like image 834
Jessie Avatar asked Jan 26 '18 14:01

Jessie


People also ask

How do I return a promise object?

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 does promise return in angular?

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.

How do I return a value from Promise TypeScript?

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.

What is a promise return type?

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.


1 Answers

Just return a Promise the resolves itself immediately.

private getStudyPeriods(): Promise<CurrentPeriod> {
    let data = [];

    return new Promise(resolve => {
        resolve(data);
    });
}
like image 118
martin Avatar answered Sep 21 '22 18:09

martin