Reputation: 1642
I have the following code that I would like to use. It is a simple service that returns and array of objects. TS is reporting the following error at the line with return new Promise...
error TS2322: Type '{}' is not assignable to type 'UserPurchasedPlan[]'. Property 'includes' is missing in type '{}'.
Below is the code that I have attempted. Working in Angular 5.2 and CLI version 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;
}
);
}
}
Upvotes: 1
Views: 73
Reputation: 611
Wouldn't it be easier to just convert the Observable
from this._paymentService.GetPurchasedPlans()
to a Promise
with toPromise()
?
Then you can change the ngOnInit()
to:
ngOnInit() {
this.GetPurchasedPlans().toPromise().then(
plans => {
this.purchasedPlans = plans;
}
).catch((err) => console.log('Error: %s', err));
}
whole class:
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));
}
}
Upvotes: 1
Reputation: 1053
You can do something like this instead:
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();
}
Upvotes: 0