Issue
I am trying to make some radio buttons in my Angular page that get their value from an API call and am having some trouble with it.
My code does not compile and is showing me these errors in the console:
Type 'boolean' is not assignable to type '[{ name: string; value: number; default: number; }]'. [ng] [ng] 103
this.preSelectedPaymentOptions = this.paymentMethod.payments.default === 1;Property 'default' does not exist on type '[{ name: string; value: number; default: number; }]'. [ng] [ng] 103
this.preSelectedPaymentOptions = this.paymentMethod.payments.default === 1;Property 'name' does not exist on type '[{ name: string; value: number; default: number; }]'. [ng] [ng] 105
console.log('Metoda plačila: ',this.paymentOptions.name);
My data looks like this in console.log:
hasACashDiscount:0
payments: Array(2)
0: {name: 'Card', value: 0, default: 1}
1: {name: 'Cash', value: 3, default: 0}
I have created a model.ts file. It looks like this:
export interface PaymenyOptions {
hasACashDiscount: number;
payments: [{
name: string;
value: number;
default: number;
}];
}
In my component.ts file this is how I'm getting the data from the API call subscription:
getPaymentOptions() {
this.cartService.getPaymenyOptions().subscribe(
data => {
this.paymentMethod = data;
this.paymentOptions = this.paymentMethod.payments;
this.preSelectedPaymentOptions = this.paymentMethod.payments.default === 1;
console.log('All data: ', this.paymentMethod);
console.log('Payment methods: ',this.paymentOptions.name);
console.log('Preselected method: ', this.preSelectedPaymentOptions);
}, error => {
console.log('Error', error);
});
}
and this is how I'm showing it in HTML:
<ion-item *ngFor="let payment of paymentOptions;let i = index">
<ion-icon name="today-outline"></ion-icon>
<ion-label>{{ payment.name }}</ion-label>
<ion-radio slot="end" [value]="payment.value"></ion-radio>
</ion-item>ž
What have I done wrong?
Solution
paymentMethod.payments
is an array.
To get (filter) the objects with default === 1
, you should use Array.filter()
method.
this.preSelectedPaymentOptions = this.paymentMethod.payments.filter(x => x.default === 1);
To get the objects' names as an array, you have to use Array.map()
method.
console.log('Payment methods: ',this.paymentOptions.map(x => x.name);
export interface PaymenyOptions {
hasACashDiscount: number;
payments: [{
name: string;
value: number;
default: number;
}];
}
Based on your current interface, the payments
property is an array but expects a single object only. You should modify it to:
export interface PaymenyOptions {
hasACashDiscount: number;
payments: {
name: string;
value: number;
default: number;
}[];
}
to allow the array can have multiple objects.
Answered By - Yong Shun
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.