简体   繁体   中英

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

      }
    })
  }

Just return a Promise the resolves itself immediately.

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

    return new Promise(resolve => {
        resolve(data);
    });
}
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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM