I have a below class Invoice
with some data and methods in it but when I assign REST API array response to my component class array I observe that angular Invoice
class methods like addItem, removeItem are not available.
I’ve tried this angular class method not working when populated by service but did not work for me.
Have a look at the below code,
1. Invoice class (angular class)
import { Customer } from "./customer";
import { InvoiceItem } from "./invoice_item";
import { Item } from "./item";
export class Invoice {
invoiceId?: number;
invoiceNumber: number;
customer: Customer;
invoiceItem: InvoiceItem[] = [];
constructor(customer?: Customer, invoiceNumber?: number) {
this.customer = customer;
this.invoiceNumber = invoiceNumber;
this.invoiceItem.push({itemId: 0, quantity: 0, rate: 0}); // default invoice_item
}
addItem() {
this.invoiceItem.push({itemId: 0, quantity: 0, rate: 0}); // default invoice_item
}
removeItem(item) {
this.invoiceItem.splice(this.invoiceItem.indexOf(item), 1);
}
}
2. Component Class(angular)
import { Component } from '@angular/core';
import { ActivatedRoute, Router } from '@angular/router';
import { Subject, Subscription } from 'rxjs';
import { Customer } from 'src/app/model/customer';
import { Invoice } from 'src/app/model/invoice';
import { InvoiceService } from 'src/app/services/invoice.service';
@Component({
selector: 'app-admin-invoices',
templateUrl: './admin-invoices.component.html',
styleUrls: ['./admin-invoices.component.css']
})
export class AdminInvoicesComponent {
customerInvoices: Invoice[] = [];
customerId: number;
constructor(private route: ActivatedRoute,
private invoiceService: InvoiceService) {
this.customerId = (this.route.snapshot.paramMap.get('customerId'));
this.invoiceService.getCustomerInvoices(this.customerId)
.subscribe((invoices: Invoice[]) => {
this.customerInvoices = invoices; // assigning service response
});
}
}
In the below image you can see service response. Also, we can see the **constructor**
of type Object
instead of type **Invoice**
even if we have declared our customerInvoices
array of type Invoice as customerInvoices: Invoice[] = [];
in our component class.
Expected Output is as below: