lapadets
lapadets

Reputation: 1095

Refactoring to make an Angular component better

I have the following Angular component written in Typescript:

export class ItemsComponent implements OnInit {

@Input()
invoice: Document;

@Input()
declaration: Document;

private invoiceName: string;
private declarationName: string;

constructor(private dataService: DataService) {
}

ngOnInit(): void {
    this.getInvoiceName(this.invoice);
    this.getDeclarationName(this.declaration);
}

getDeclarationName(declaration: Document) {
    this.dataService.getDocumentName(declaration.id)
        .subscribe((name) => this.declarationName = name);
}

getInvoiceName(invoice: Document) {
    this.dataService.getDocumentName(invoice.id)
        .subscribe((name) => this.invoiceName = name);
}

I have two items of the same type but I get them as inputs from different components and then I use them in my html template separately. What I have right now is fine and works, but I find it too repetitive and it smells to me.

Do you have any idea how I can refactor it, so that I get just one method like getDocumentName for example and I can call it once inside the onInit but get the names of my invoice and my declaration separately?

Upvotes: 0

Views: 189

Answers (1)

Hugo Noro
Hugo Noro

Reputation: 3243

You can do something like this

ngOnInit(): void {
    this.getDocumentNames();
}

getDocumentNames() {
    this.dataService.getDocumentName(this.declaration.id)
        .subscribe((name) => this.declarationName = name);
    this.dataService.getDocumentName(this.invoice.id)
        .subscribe((name) => this.invoiceName = name);
}

Then on the dataservice level you can do a share to optimize the http calls.

Or since you want to retrieve multiple names at the same time you can consider changing the dataService to support a method that receives an array of Ids and make only one call on the component

Upvotes: 1

Related Questions