我有以下要使用的代码。这是一个简单的服务,它返回对象和对象数组。 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;
}
);
}
}
答案 0 :(得分:1)
使用Observable
将this._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();
}