返回订阅结果作为承诺

时间:2019-01-10 15:01:41

标签: angular typescript

我有以下要使用的代码。这是一个简单的服务,它返回对象和对象数组。 TS在return new Promise...

行报告了以下错误

error TS2322: Type '{}' is not assignable to type 'UserPurchasedPlan[]'. Property 'includes' is missing in type '{}'.

下面是我尝试过的代码。在Angular 5.2和CLI版本1.6.8中工作。

export class LicensesComponent implements OnInit {

  constructor(private _paymentService: PaymentService) { }

  purchasedPlans: UserPurchasedPlan[] = [];

  async GetPurchasedPlans(): Promise<UserPurchasedPlan[]> {
    return new Promise((resolve, reject) => {
      const sub = this._paymentService.GetPurchasedPlans().subscribe(
        response => {
          resolve(response);
          sub.unsubscribe();
        },
        err => {
          reject(err);
          sub.unsubscribe();
        }
      );
    });
  }

  ngOnInit() {
    this.GetPurchasedPlans().then(
      plans => {
        this.purchasedPlans = plans;
      }
    );
  }

}

2 个答案:

答案 0 :(得分:1)

使用Observablethis._paymentService.GetPurchasedPlans()Promise转换为toPromise()会更容易吗? 然后,您可以将ngOnInit()更改为:

ngOnInit() {
  this.GetPurchasedPlans().toPromise().then(
    plans => {
      this.purchasedPlans = plans;
    }
  ).catch((err) => console.log('Error: %s', err));
}

全班:

export class LicensesComponent implements OnInit {

  constructor(private _paymentService: PaymentService) { }

  purchasedPlans: UserPurchasedPlan[] = [];

  ngOnInit() {
    this._paymentService.GetPurchasedPlans().toPromise().then(
      plans => {
        this.purchasedPlans = plans;
      }
    ).catch((err) => console.log('Error: %s', err));
  }
}

答案 1 :(得分:0)

您可以改为执行以下操作:

async GetPurchasedPlans(): Promise<UserPurchasedPlan[]> {
  return this._paymentService.GetPurchasedPlans()
    .pipe( 
        map((response) => {  // <- Import this map from 'rxjs/operators'
            const mappedResponse: UserPurchasedPlan[] = [] // <- Here you need to map your response to UserPurchasedPlan[]
            return mappedResponse;
        })
    ).ToPromise();
}