What strategies can I implement in Angular to enhance the efficiency of my code and reduce load time? Presently, the load time stands at 2

I'm looking to enhance the performance of my code to increase speed. How can I optimize the following code snippet to further improve load time? Additionally, any suggestions on what considerations I should keep in mind would be greatly appreciated. Currently, the finish time is 2.45sec.

TS

export class AppComponent implements OnInit {
  searchKeywords: string;
  CoffeeItemList: any = [];
  type: string;
  search: string;
  selectedType = '';
  showLoader: boolean;
  empty = false;
  data: any = [];

  // tslint:disable-next-line:max-line-length
  constructor(private getDataListingService: DataListingService) {}
  ngOnInit(): void {
    this.getGlobalSearchList('');
    this.getAllData();
    this.getSmartSearchValues('');
    if (this.CoffeeItemList.length === 0) {
      this.empty = true;
      }
  }
  getAllData() {
    this.showLoader = true;
    this.getDataListingService.getAllDataLists().subscribe(value => {
      this.CoffeeItemList = value.data;
      this.showLoader = false;
    });
  }
  getGlobalSearchList(type: string) {
    this.selectedType = type;
    this.CoffeeItemList = [];
    this.getDataListingService.getAllDataLists().subscribe(value => {
        this.data = value.data;
        console.log(this.data);
        // tslint:disable-next-line:prefer-for-of
        for (let i = 0; i < this.data.length; i++) {
            if (this.data[i].type === type) {
                this.CoffeeItemList.push(this.data[i]);
            }
        }
    });
}
getSmartSearchValues(search: string) {
  if (search === '' ) {
      this.getAllData();
      return false;
  }
  if (search.length >= 3) {
    this.getDataListingService.searchList(search).subscribe(value => {
        this.data = value.data;
        this.CoffeeItemList = value.data;
        // check selected type either coffee, mobile or ALL.
        if (this.selectedType && this.selectedType !== '' ) {
            this.CoffeeItemList = [];
            // tslint:disable-next-line:prefer-for-of
            for (let i = 0; i < this.data.length; i++) {
                if (this.data[i].type === this.selectedType) {
                    this.CoffeeItemList.push(this.data[i]);
                }
            }
        }
    });
  }
}
}

Answer №1

It appears that the getDataListingService is being called three times in the ngOnInit() function, resulting in multiple requests and data manipulation.

It may be beneficial to review your HTML file to determine if all the requests are necessary on initialization.

Answer №2

Why are you calling getAllDataLists twice? Can't one of these subscriptions be eliminated to streamline the process?

Try filtering out more data before loading it into your application. A one-second call is a significant amount of data, so consider filtering getAllDataLists beforehand. It's possible that either there is too much data being transmitted, causing slow network speeds, or the HTML is overly complex and loading excessive amounts of data, leading to sluggish performance.

It seems like you may be repeating the same mistakes with subscriptions. Keep in mind that subscriptions trigger every time data is changed. If you are subscribing to every keyup event in your current setup, you may inadvertently create numerous subscriptions that never complete and continuously poll for changes.

Answer №3

After reviewing the code you shared:

  1. It is recommended to incorporate pagination in the 'getAllDataLists' and 'searchList' methods to handle large data sets more efficiently and improve user experience.
  2. Consider consolidating multiple API calls into a single request to minimize memory usage and speed up data rendering on the UI. These methods can be combined into one:

    this.getGlobalSearchList('');
    this.getAllData();
    this.getSmartSearchValues('');
    
  3. To optimize the API call, consider including the 'selectedType' parameter in the API request to streamline data retrieval from the backend without the need for additional checks like

    if (this.selectedType && this.selectedType !== '' )

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

What is the relationship between JavaScript node modules and vanilla script references within the browser environment?

When using the modular javascript approach with Node.JS + npm and browserify, how do you handle situations where you need to use javascript libraries that are not available on npm? Some of these libraries may not be compatible with modularity (amd/commonJs ...

Animating with React JS using JSON data sources

Currently, my project involves using React/Redux to store animation data in JSON and display it on a React page. The challenge lies in implementing the animations correctly while utilizing setTimeout for pauses and setInterval for movement. The Animation ...

Filtering arrays of objects dynamically using Typescript

I am looking to create a dynamic filter for an array of objects where I can search every key's value without specifying the key itself. The goal is to return the matched objects, similar to how the angular material table filters all columns. [ { ...

What is the best way to permit multiple instances of a component in separate tabs without losing their individual states?

My application is equipped with a lazy loading tab system that is controlled by a service. When a user chooses an option from the navigation menu, two key actions take place : An entry is appended to the tabs array within the tab service. A new route is t ...

The transition to Angular 7 has caused complications with the Octopus deployment process

Situation Working on an Angular 4.3 project that is built using Jenkins Utilizing "octo.exe pack ..." step to package output into a NuGet package Using Octopus for deployment to IIS Issue at Hand After upgrading the project to Angular 7, encountering ...

What is causing the WebMvc ProfileController to be visible and disrupting the functionality of my static website?

I am currently running an Angular application within a Spring Boot application. When accessing routes like https://localhost:8081/sign-in https://localhost:8081/invalid-url (which redirects to PageNotFoundComponent) everything works fine. However, when ...

Material-UI Slide component is encountering an issue where it is unable to access the style property of an undefined variable

Recently, I incorporated Material-UI Slide into my project and I'm curious about why the code functions correctly when written in this manner: {selectedItem && selectedItem.modal && selectedItem.modal.body ? ( selectedItem.modal.body.map((section ...

Retrieve data from submit button in Angular and use it as a parameter to invoke a function

I am working on a HTML file that includes a dropdown list: <select> <option *ngFor="let t of items" value="t"> {{ t }} </option> </select> In addition to the dropdown list, there ...

Is there a way to trigger a function in an AngularJS controller from a Backbone controller?

I've been working on an application that was originally developed using backbone and jQuery, but we had to incorporate new modules built with angular to meet client requirements. Routing in the application is handled by backbone route, and we have suc ...

When starting a new project with Angular 7, the option to set up routing is automatically included without asking for confirmation

After switching from Angular 6 to version 7, I encountered an issue while creating a new project in CLI using ng new [app-name]. It simply starts without giving me the option to include routing or styling in my project. Just a heads up, I am currently run ...

What steps can you take to address Git conflicts within the yarn.lock file?

When numerous branches in a Git project make changes to dependencies and use Yarn, conflicts may arise in the yarn.lock file. Instead of deleting and recreating the yarn.lock file, which could lead to unintended package upgrades, what is the most efficie ...

Using JQuery to Update Text, Link, and Icon in a Bootstrap Button Group

I have a Bootstrap Button group with a split button dropdown. My goal is to change the text, href, and icon on the button when an option is selected from the dropdown. I am able to change the text successfully, but I'm having trouble updating the HREF ...

Can the z-index property be applied to the cursor?

Is it possible to control the z-index of the cursor using CSS or Javascript? It seems unlikely, but it would be interesting if it were possible. Imagine having buttons on a webpage and wanting to overlay a semi-transparent image on top of them for a cool ...

Encountered an error while trying to click the cookie button using Selenium: "object[] does not have a size or

I've been struggling to interact with a button inside a pop-up using Selenium, but I keep encountering this error: object [HTMLDivElement] has no size and location I initially tried to simply click the button since it is visible on the page and I wai ...

How to embed a multidimensional JSON or array into another multidimensional JSON or array using PHP

Looking to include sub data in JSON format using a foreach loop For example: Each house contains one or more rooms Room data is within the respective house Here is the code snippet: <?php $houses = Houses::find()->all(); foreach($houses AS $hou ...

Alerts being used by Jquery Validation Engine to showcase errors

In the validation engine, my goal is to have error messages appear in a JavaScript alert box instead of as small tooltips right next to the input fields. $("#main_form").bind("jqv.form.result", function(event, errorFound) { if(errorFound) aler ...

Use the res.json method in express.js to automatically generate a predefined response structure

I'm looking for guidance on how to properly use res.json in my code. I want to establish a default response structure that includes a message and error, while also being able to include additional data when necessary. For example, when I use res.statu ...

Ways to share code across AngularJS frontend and Node.js backend

How can code be effectively shared between an AngularJS client and a Node.js server? After creating an AngularJS application, I now need to develop a RESTful server to provide data to the client. Some Angular services used on the client-side could also be ...

Utilize Jasmine to spy on an inner function and return a mock value from the last function call

I'm currently working on a Jasmine test where I have an object structure like this: class User { public getData(): void { return { getPersonalInfo: () => { ... } } } } Typically, I would access it as ...

Increase the ngClass attribute's value

Is there a way to automatically increment a numeric value in a class using the ngClass directive? For example, can we achieve something like this: <some-element [ngClass]="'class-*'">...</some-element>, where the asterisk (*) will in ...