Angular method containing reusable object

I have a simple list where I want to optimize my code by only updating the admin2 object once. The goal is for admin2 to be set equal to (property) Admin2Component.admin2: IAdmin2:

In simpler terms, I need to update this admin2 with three different pagination objects: projectPagination, consultantPagination, and newsletterPagination.

private updateList(
    projectPagination: IPaginationResponse <IProject>,
    consultantPagination: IPaginationResponse <IConsultant>,
    newsletterPagination: IPaginationResponse <INewsletter>
) {
    this.admin2 = projectPagination.data;
    this.pagination.total = projectPagination.meta.pagination.total;
    this.pagination.page = projectPagination.meta.pagination.current_page;

    this.admin2 = consultantPagination.data;
    this.pagination.total = consultantPagination.meta.pagination.total;
    this.pagination.page = consultantPagination.meta.pagination.current_page;

    this.admin2 = newsletterPagination.data;
    this.pagination.total = newsletterPagination.meta.pagination.total;
    this.pagination.page = newsletterPagination.meta.pagination.current_page;
}

Later on:

$onInit() {
    console.log(this.projectPagination, this.consultantPagination,
    this.newsletterPagination);
    this.updateList(
        this.projectPagination,
        this.consultantPagination,
        this.newsletterPagination
    );
}

Answer №1

My interpretation leads me to believe that you are dealing with 3 distinct sets of pagination values and you need to incorporate all 3 within your component. However, your current approach involves repeatedly assigning one set of class properties to each of the 3 values in succession. This methodology will not yield the desired outcome as your class properties will continuously reflect the last assignment made.

To address this issue, consider generating 2 additional sets of class properties. Your initial structure may resemble something along the lines of:

class MyClass {
    admin2: any;
    pagination: any;

    // ...
}

You should transform it into a more comprehensive layout (remember to allocate more distinctive names, adhering to your existing naming convention):

class MyClass {
    admin: IProject;
    pagination: IPaginationResponse<IProject>;

    admin2: IConsultant;
    pagination2: IPaginationResponse<IConsultant>;

    admin3: INewsletter;
    pagination3: IPaginationResponse<INewsletter>;

    // ...
}

This restructuring affords you 3 separate sets of class properties, each corresponding to a distinct pagination object for your components.

Next, modify your updateList function to assign all 3 sets of properties instead of iteratively reassigning the same set thrice:

private updateList(
    projectPagination: IPaginationResponse <IProject>,
    consultantPagination: IPaginationResponse <IConsultant>,
    newsletterPagination: IPaginationResponse <INewsletter>
) {
    this.admin = projectPagination.data;
    this.pagination.total = projectPagination.meta.pagination.total;
    this.pagination.page = projectPagination.meta.pagination.current_page;

    this.admin2 = consultantPagination.data;
    this.pagination2.total = consultantPagination.meta.pagination.total;
    this.pagination2.page = consultantPagination.meta.pagination.current_page;

    this.admin3 = newsletterPagination.data;
    this.pagination3.total = newsletterPagination.meta.pagination.total;
    this.pagination3.page = newsletterPagination.meta.pagination.current_page;
}

Prioritize the instantiation of your class properties to prevent them from defaulting to undefined, thereby avoiding errors such as "cannot access foo of undefined" when attempting operations like this.pagination.foo.

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

PhpStorm alerts users to potential issues with Object methods within Vue components when TypeScript is being utilized

When building Vue components with TypeScript (using the lang="ts" attribute in the script tag), there is a warning in PhpStorm (version 2021.2.2) that flags any methods from the native JavaScript Object as "Unresolved function or method". For exa ...

Showing a ng2-pdf-viewer PDF contained within a stream

My webpage integrates the ng2-pdf-viewer library: <pdf-viewer [src]="fileToDownload" [render-text]="true" style="display: block;"></pdf-viewer> A Node API is used to fetch the PDF file and return a URL: this.httpC ...

Using ngmodel in Angular to assign a value to the Angular Material datepicker

Having an issue with editing the selected value in a custom control value accessor for an Angular Material date component. The input field is returning empty. App.Component.Html <date-input ngModel="dateValue" name="dateName"> ...

How to deploy two applications using a single codebase in Ionic 2

My Ionic 2 application has become quite complex and I feel the need to divide it into separate apps, one for the GUI and another for the services. Both apps will be based on the same codebase. The GUI app will encompass the functionalities of the service a ...

Exploring Aurelia's Integration with ASP.NET Core Models

Recently, I've been delving into various JavaScript frameworks and made the decision to rework an ASP.Net Core MVC frontend using Aurelia. To kick things off, I utilized the SPA template. Everything has been smooth sailing so far - I’ve integrated ...

Prevent all dates from being selected except for the last day of every month in the Angular Material Calendar component

Is it possible to restrict all dates except the final day of each month with Angular Material? I need users to only be able to select this particular date. There is a [matDatepickerFilter] property, but it seems to work only for a specific list of dates. ...

An error is being thrown in the Angular build due to an issue with parsing JSON after stripping out

Currently, I am working with angular nx alongside nestjs. Upon cloning the project and executing the yarn command, it successfully builds. However, whenever I try to install any package and compile the project, an error is thrown: **D:\projectNAme&bso ...

Strategies for handling multiple HTTP requests in Angular using RXJS

Within this demonstration application, we have the following structure: A list of articles (loaded upon page initialization) Each article contains a nested object called detail, which is loaded lazily Clicking on an article item will load its details. H ...

Expanding a TypeScript interface across different modules

For my project, I am working with Highcharts typings and encountered a need to extend certain object/interfaces it defines by adding some custom properties. Here is an example: declare namespace Chart { interface ChartOptions extends Highcharts.ChartOpt ...

Angular router consistently redirecting to the identical module

It's really frustrating me. I've set up 3 basic routes in my app module: routes: Routes = [ { path: '', redirectTo: '/customers', pathMatch: 'full' }, { path: 'customers', loadChildren: './com ...

Warning: Installing packages with names containing "esbuild-" using npm may

After upgrading my Angular version from 10 to 12 using the steps provided at https://update.angular.io/?l=3&v=10.0-12.0, I successfully completed every step. However, upon running npm install, I encountered the following warnings: npm WARN optional SKI ...

How can I access members outside of a class without a name in Typescript?

I recently developed an "anonymous" class inspired by this insightful discussion on Typescript anonymous classes. However, I'm facing a challenge in accessing the outer scope members. Here's a snippet of my code for context: class BaseCounter { ...

What is the process for developing an interface adapter using TypeScript?

I need to update the client JSON with my own JSON data Client JSON: interface Cols { displayName: string; } { cols:[ { displayName: 'abc'; } ] } My JSON: interface Cols { label: string; } { cols:[ { label:&a ...

The debounced function in a React component not triggering as expected

I am facing an issue with the following React component. Even though the raiseCriteriaChange method is being called, it seems that the line this.props.onCriteriaChange(this.state.criteria) is never reached. Do you have any insights into why this.props.onC ...

Retrieve data from a JSON object within an HTML document

How do I display only the value 100 in the following div? <div> {{uploadProgress | async | json}} </div> The current displayed value is: [ { "filename": "Mailman-Linux.jpg", "progress": 100 } ] Here is my .ts file interface: interface IU ...

What is the best way to incorporate padding into an Angular mat tooltip?

I've been attempting to enhance the appearance of the tooltip dialog window by adding padding. While adjusting the width and background color was successful, I'm encountering difficulties when it comes to styling the padding: https://i.sstatic.ne ...

Managing oAuth in the Angular user interface

I currently have a Python FastAPI Backend that provides an endpoint for retrieving oAuth data. The endpoint functions properly when accessed manually through my web browser. It initiates a redirect to fetch an accessToken, which is then used to access a se ...

Extract data from selected range using Highcharts

I am working on implementing a Highchart in Angular and I have run into an issue with creating my own range selector dynamically using this.chart.update. Unfortunately, the error "undefined update not a function" keeps popping up. How can I troubleshoot ...

Updating and saving data in Ag-Grid with server communication

Is it possible to create a grid using Ag-Grid on Angular that fetches data from a local JSON file? And how can the edited row data be saved and sent to the server or back to the local JSON file? In summary, I would like to know how to save edited row data ...

Running an ASP.NET 6.0 C# program with Angular as a service on Windows 10: A step-by-step guide

While there are numerous tutorials available online for running C# programs as services, I have been struggling to find one tailored specifically for an ASP.NET framework with a web GUI and backend server component. In my scenario, the frontend is develope ...