Jessie
Jessie

Reputation: 493

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

      }
    })
  }

Upvotes: 9

Views: 21853

Answers (2)

David Anthony Acosta
David Anthony Acosta

Reputation: 4910

private getStudyPeriods(): Promise<CurrentPeriod[]> {
    return new Promise((resolve, reject) => {
        let data: CurrentPeriod[] = [];
        resolve(data);
    });
}

I changed return type to array, since it seems you are trying to return an array of CurrentPeriod, rather than just one.

Upvotes: 2

martin
martin

Reputation: 96889

Just return a Promise the resolves itself immediately.

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

    return new Promise(resolve => {
        resolve(data);
    });
}

Upvotes: 24

Related Questions