Improving an Angular component through refactoring

Here is an Angular component written in Typescript that I am currently working on:

export class ItemsComponent implements OnInit {

@Input()
invoice: Document;

@Input()
declaration: Document;

private invoiceName: string;
private declarationName: string;

constructor(private dataService: DataService) {
}

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

getDocumentNames() {
    this.getSingleDocumentName(this.invoice, (name) => this.invoiceName = name);
    this.getSingleDocumentName(this.declaration, (name) => this.declarationName = name);
}

getSingleDocumentName(document: Document, callback: Function) {
    this.dataService.getDocumentName(document.id)
        .subscribe((name) => callback(name));
}

Although the current setup works fine, it feels repetitive and inefficient to me. I would like to refactor it so that I can have just one method like getDocumentName, which I can call once inside the onInit to retrieve the names of both my invoice and declaration separately. Do you have any suggestions on how to achieve this?

Answer №1

If you're looking to optimize your HTTP calls in Angular, here's a suggestion:

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

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

To improve efficiency, consider implementing a share method at the data service level.

If you need to retrieve multiple names simultaneously, you could enhance the data service to handle an array of IDs and make just one call from the component.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Tips for fixing the issue of 'expect(onClick).toHaveBeenCalled();' error

Having trouble testing the click on 2 subcomponents within my React component. Does anyone have a solution? <Container> <Checkbox data-testid='Checkbox' checked={checked} disabled={disabled} onClick={handl ...

Bringing together projects utilizing varying Typescript versions within Visual Studio 2015

When working with VS2015-SP2, imagine a solution that contains two typescript projects. One project is using version 1.5 and the other is using version 1.7. How will the compiler handle this situation? ...

Employing a one-time use variable that is asynchronously loaded via a React hook

Currently, I am exploring the functionalities of React's hooks, but I'm encountering a roadblock when it comes to integrating different use cases. The main goal is to create a hook called useNationsAsync that fetches a list of available nations ...

Testing the Child Component's EventEmitter Functionality

In my child component, there is an event emitter that sends a boolean value when the style changes in the parent component: export class ExampleComponent implements OnInit, OnChanges { @Output() statusEvent = new EventEmitter<boolean>(); getS ...

Struggling with slow TypeScript compilation?

My current setup involves TypeScript 2.2.1, but I've been facing prolonged compilation times when running tsc. In an attempt to gather more information, I decided to utilize the --diagnostics option. However, I soon discovered that the "Total time" di ...

Calculate input values in Angular forms and dynamically display the result by triggering an update event with onchange

Is it possible to input two values in an input element and calculate them without using a submit button but instead utilizing the change event? How can this be achieved? Here's an example of the HTML structure: <form> <div class="form-g ...

Embedding an Iframe in Angular 2 directly from the database

Looking for assistance with iframes in Angular 2. Initially, embedding an iframe directly into a component's template functions correctly. <iframe src='http://plnkr.co/edit/zZ0BgJHvQl5CfrZZ5kzg?p=preview | safeUrl' allowtransp ...

What could be causing this particular issue when using the Firestore get() method? The error message states: "ERROR TypeError: snaps

In my current Angular project, I am utilizing Firebase Firestore database and have implemented the following method to execute a query: findArtistBidsAppliedByCurrentWall(bid):Observable<Bid[]> { console.log("findArtistBidsAppliedByCurrent ...

What are the steps to organize an array of objects by a specific key?

Experimented with the following approach: if (field == 'age') { if (this.sortedAge) { this.fltUsers.sort(function (a, b) { if (b.totalHours > a.totalHours) { return 1; } }); this ...

Make sure to call the loader function in React Router only when there are path params present

I'm currently implementing the new React Router, utilizing loader functions to fetch data based on the loaded element. My goal is to have certain APIs called regardless of the route, with additional APIs triggered for specific routes. However, I&apos ...

Angular template error: 'Component' type does not have the specified property

I am facing an issue with importing an array from a file named platforms.ts. The array is declared as shown below: export const platforms: Platforms[] = [ { name: 'Instagram', value: 'instagram' }, { name: 'Facebo ...

An array comprising multiple arrays containing strings

I need help creating a nested array of strings like the one shown below: let rules : type = [ ["N"] ["N", "N"] ["N", "N", "N"] ] I'm struggling to set the correct type for this array. Can you assist me with this? ...

Angular Material Slide-Toggle Takes Too Long to React

In my project, I am facing an issue with a control panel that contains an Angular Mat-Slide-Toggle element. Here is the code snippet: <mat-slide-toggle (change)="onQAStateDisplayChanged($event)">Display QA Status</mat-slide-toggle> When the c ...

Trapped in the Google Maps labyrinth (Angular)

Hey there everyone! I'm currently working on an exciting angular application that integrates the Google Maps API. The goal is to create a feature that shows the 20 closest coffee shops based on the user's current location. However, I seem to be r ...

Angular 6 triggers NavigationCancel event when encountering valid guards

I'm encountering difficulties with the Angular router while trying to navigate to a specific state. Despite my attempts to utilize a custom guard with canLoad() and canActivate() functions that return true, I have not been successful. The Angular do ...

Display Picture Based on Identifier from LocalStorage in Angular 4

Is it possible to use the user's ID from local storage to determine which image should be displayed? In my AngularJS app, I have a list of images stored in the assets/ folder. How can I retrieve the current user's ID and use that as a reference f ...

Exploring Next JS: Effectively altering SVG attributes and incorporating new elements

I have integrated SVGR to load an SVG as a component in my latest Next.js 13 application: import CvSvg from './../../public/image.svg' export default function Home() { return ( <div className="flex flex-col min-h-screen" ...

Is there a way to prevent nesting subscriptions in rxjs?

Currently, I am working with a code that contains nested subscribes: .subscribe((data) => { const { game, prizes } = data; this.ticketService.setListOfTickets(game.tickets); this.ticketService.getListOfTickets() .subscribe((data: any) => { ...

Using Angular CLI to create a new project with SASS from an existing project

After diving into a project generated by Angular CLI, I realized I forgot to include the --style=sass flag. Is there a method to transition my project to support SASS using Angular CLI? ...

An alternative way to show time zones such as PT and ET instead of using PST and EST with the help of moment

For efficiency in table space using moment.js, I am looking to utilize PT/ET instead of PST/EST. HTML- {{ moment.tz([2012,0],timezone).format('z')}} // It displaying EST/PST but I need only ET/PT. Note: The timezone is dynamic, so regardless of ...