Avoid making API calls in every ngOnInit() function

I am currently developing an Angular front-end for a web-based application. One of the challenges I am facing is that all sub-page drill downs, implemented as different Angular components, make identical API calls in the ngOnInit() method. This repetitive calling is causing performance issues as the user traffic increases. I am seeking a solution to cache this data so that it can be utilized across multiple pages, thereby reducing the number of API requests.

ngOnInit() {
    if (this.api.validInputParams()) {
        this.api.getLiveData().subscribe((response) => {
            // Perform page-specific functionality and filtering

        }, (error) => {
            // Any errors should be handled by the HttpInterceptor
        });
    }
}

Answer №1

To effectively leverage the API, integrate it once at the top level component and connect with sub pages using @Input(), establishing one-way data binding. Start at the top level component :

top-component.ts (initiate the API call and store the results in a variable)

public response;

ngOnInit() {
  this.api.getData().subscribe(response => this.response = response);

top-component.html (pass the data to the sub-page)

<app-children [response]="response"></app-children>

sub-page (access the data from the input)

@Input() response;

Answer №2

One simple approach is to utilize 2-Way-DataBinding for passing them down easily. If that method isn't an option, a straightforward solution would be to store it in the local storage using

localStorage.setItem('data', JSON.stringify(yourData);
and for retrieval, you can utilize
yourData = JSON.parse(localStorage.getItem('data'));

Answer №3

To avoid unnecessary updates, store the data in your system and only retrieve it when needed instead of making repeated HTTP calls. Consider saving the timestamp of the last update, and only initiate a call if there has been a significant time difference since the last update.

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

Modifying the property value based on the selected item from a dropdown menu in Angular 2

I am brand new to Angular 2 and I have come across the following code snippet. <select name="shape_id" (change)="changeShape()"> <option *ngFor="let shape of shapes" [ngValue]="shape.name"> {{shape.name}} </option> </s ...

Angula 5 presents a glitch in its functionality where the on click events fail

I have successfully replicated a screenshot in HTML/CSS. You can view the screenshot here: https://i.stack.imgur.com/9ay9W.jpg To demonstrate the functionality of the screenshot, I created a fiddle. In this fiddle, clicking on the "items waiting" text wil ...

When using the map function, I am receiving an empty item instead of the intended item based on a condition

Need assistance with my Reducer in ngRx. I am trying to create a single item from an item matching an if condition, but only getting an empty item. Can someone please help me out? This is the code for the Reducer: on(rawSignalsActions.changeRangeSchema, ...

Even after ensuring the proper type checking, I am still receiving the error message "Property 'message' does not exist on type 'object'"

I have the following code snippet: try { // api call } catch (error) { if (typeof error === 'object' && error !== null && 'message' in error) { if (typeof error.message === 'string') { if (error.me ...

Error: The JSON file cannot be located by the @rollup/plugin-typescript plugin

I have recently set up a Svelte project and decided to leverage JSON files for the Svelte i18n package. However, I am facing challenges when trying to import a JSON file. Although the necessary package is installed, I can't figure out why the Typescri ...

Retrieve the text content of the <ul> <li> elements following a click on them

Currently, I am able to pass the .innerTXT of any item I click in my list of items. However, when I click on a nested item like statistics -> tests, I want to display the entire path and not just 'tests'. Can someone assist me in resolving this i ...

Troubleshooting AngularJS2 and npm in WebStorm and Chrome for Windows users

Having completed the official Hero tutorial for AngularJs2 using Visual Studio Code, I decided to switch my coding and debugging setup to WebStorm+Chrome on Windows 10. To achieve this transition, I took the following steps: Installed Chrome JetBrains ...

Exploring the TypeScript handbook: Utilizing rootDirs for Virtual Directories

Exploring the concept of Virtual Directories with rootDirs in the handbook, we find an interesting example demonstrating how modules can be imported from different source folders by combining multiple rootDirs. // File Structure src └── views ...

Encountering the error "RouterOutletMap provider not found" while using angular-cli version 1.0.0-beta.10

I am facing confusion while trying to set up routing for angular-cli version 1.0.0-beta.10, using @angular/router version 3.0.0-beta.2. I encountered an error message stating 'No provider for RouterOutletMap'. Any assistance in resolving this iss ...

"Angular Google Maps module working perfectly on local environment but failing to render on live production site

My little application utilizes the official Angular Google Maps module. While it runs smoothly in my local setup, it simply displays a gray window in production. Upon inspecting the code, I can see that the map, marker, and info window are present, but not ...

Cordova's FileReader takes precedence over TypeScript's FileReader functionality

I encountered an issue when adding the cordova-plugin-file-transfer plugin, where I received the error message: reader.addEventListener is not a function. This problem arises due to Cordova FileReader class overriding typescript FileReader. How can this ...

Tips on implementing computed properties in Vue.js while using TypeScript

There is a significant amount of documentation on how to utilize Vue.js with JavaScript, but very little information on using TypeScript. The question arises: how do you create computed properties in a vue component when working with TypeScript? According ...

The member 'email' is not found in the promise type 'KindeUser | null'

I'm currently developing a chat feature that includes PDF document integration, using '@kinde-oss/kinde-auth-nextjs/server' for authentication. When trying to retrieve the 'email' property from the user object obtained through &apo ...

Ways to observe redux action flow within a component

I am currently developing a React application structured with the following elements: redux typesafe-actions redux-observable My query is: How can I trigger a UI action when a specific redux action occurs? For instance, if we have these asynchronous ac ...

NgFor is designed to bind only to Iterables like Arrays

After exploring other questions related to the same error, I realized that my approach for retrieving data is unique. I am trying to fetch data from an API and display it on the page using Angular. The http request will return an array of projects. Below ...

Link Array Element to [(value)] within Angular

Hey there! I'm currently working with Angular Material and dealing with an Array of products to generate a table in my template. <tbody> <tr *ngFor="let item of productArray | async; let i = index"> Within this loop, I have another l ...

Issue: Unhandled promise rejection: NullInjectorError: R3InjectorError(AppModule)[baseURL]

I need some assistance with Angular HTTP as I am facing an issue. I am attempting to retrieve JSON data and images from a JSON-server using the command line. After running 'json-server --watch db.json' in the cmd, I encountered the following: Se ...

What is the process for turning off deep imports in Tslint or tsconfig?

Is there a way to prevent deep imports in tsconfig? I am looking to limit imports beyond the library path: import { * } from '@geo/map-lib'; Despite my attempts, imports like @geo/map-lib/src/... are still allowed. { "extends": &q ...

Guide to highlighting manually selected months in the monthpicker by utilizing the DoCheck function in Angular

I'm facing an issue and I could really use some assistance. The problem seems quite straightforward, but I've hit a roadblock. I have even created a stackblitz to showcase the problem, but let me explain it first. So, I've developed my own t ...

Using Angular and Typescript to Submit a Post Request

I am working on a basic Angular and Typescript page that consists of just one button and one text field. My goal is to send a POST request to a specific link containing the input from the text field. Here is my button HTML: <a class="button-size"> ...