What are the best practices for storing and accessing data in an Angular 9 application to ensure it can be

I have developed an angular application where the list of categories is loaded on the home page. To achieve this, I am calling the getCategories() function on ngOnInit, so every time the home page is visited, all categories are fetched from the database and displayed. While this functionality works correctly, a problem arises when a user navigates to a specific category page from the home page and then returns back to the home page. In such instances, the app fetches all categories from the database and renders them again on the home page. As a result, the app ends up making multiple http requests every time the home page is revisited.

Hence, my query is whether there exists a technique or method to eliminate these redundant http Get calls. Is there a way to store the retrieved data once the home page is initially loaded, perhaps in a local scope, so that whenever the user returns to the home page, the data can be fetched from this stored location rather than querying the database again?

Answer №1

To ensure data preservation when navigating away from components, it's important to store the data in a more globally accessible manner. Utilizing Angular's root-provided services is the recommended approach. An example implementation could be as follows:

@Injectable({providedIn: 'root'})
export class MyRequestService {
   private myRequest?:Observable<MyResponseType>;
   
   constructor(private httpClient:HttpClient) {}

   public doRequest():Observable<MyResponseType> {
      if (!this.myRequest) {
          this.myRequest = this.httpClient.get('http://someurl.de').pipe(
             shareReplay(1)
          )
      }
      return this.myRequest;
   }
}

Simply call the doRequest method in your component instead of handling the request directly.

@Component({ /*...*/ })
export class MyComponent implements OnInit {
   public myData?:MyResponseType;

   constructor(private myRequestService:MyRequestService) {}

   public ngOnInit():void {
      this.myRequestService.doRequest()
         .subscribe(myData => this.myData = myData);
   }
}

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

Is tsconfig.json Utilized by Gatsby When Using Typescript?

Many blog posts and the example on Gatsby JS's website demonstrate the use of a tsconfig.json file alongside the gatsby-plugin-typescript for TypeScript support in Gatsby. However, it seems like the tsconfig.json file is not actually utilized for conf ...

Creating Unique Local Types without Compatibility Issues in TypeScript

TypeScript Version: 3.8.2 Search Terms: map, over, utility, type, result, keys, extract Code The following helper function is functioning beautifully for me: export type ComputeUnionValue<V extends AnyCodec[]> = { [i in Extract<keyof V, num ...

Styling Angular parent and child components: Best practices for consistent design

I'm currently expanding my skills in Angular 18, even though I am already familiar with React. In my project, I have a rather extensive HTML file that I would like to break down into smaller components. Here is a simplified and minified example: <u ...

Employing Multer and Express in conjunction with TypeScript

Overview Currently, I am working on a project that involves creating a user-friendly website where individuals can easily upload images. For this particular task, I have employed Node.js, React, Multer, and Typescript. Issue at Hand app.post('/admi ...

Enforcing type changes in TypeScript

One of my functions is designed to detect if a value could be a number and then convert it to Float if possible. This function comes in handy especially when converting data from CSV to JSON, where everything gets stringified. const possibleNum: string | n ...

Tips for dynamically calling a property member of a function type in Typescript

How can I determine if a member is a function in TypeScript? Is dynamic typing discouraged in TypeScript? function checkIfFunction<T, K extends keyof T>(obj: T, propName: K) { if (typeof obj[propName] === "function") { obj[p ...

What could be causing the availability of a response in a service, but showing as undefined in the component?

Currently, I am facing a problem with my service and component setup. While the service can successfully read the response as a JSON object, the component is returning res: undefined. service: constructor( private http: Http, private fbuilder: Fo ...

Exploring the functionality of Kendo Grid within an Angular application

Currently, I am facing some challenges while trying to execute my Karma tests using the kendo grid within a fresh Angular project. The specifications for this specific component are outlined below: import { async, ComponentFixture, TestBed } from '@a ...

Is it feasible to create type-safe callbacks in the style of Node.js?

Node callbacks typically have a structure like this: interface NodeCallback<TResult,TError> { (err: TError): void; (err: null, res: TResult): void; } With the callback receiving either an err or res, but not both. Many type definitions I'v ...

Is there a problem with the npm installation due to the absence of Xcode or CLT version?

"There seems to be no receipt for 'com.apple.pkg.cltools_executables' located at '/'" This error occurs during the execution of 'npm install' for an Angular 9 project in the VS Code terminal on MacOS (Catalina) Her ...

Can you identify the reason for the hydration issue in my next.js project?

My ThreadCard.tsx component contains a LikeButton.tsx component, and the liked state of LikeButton.tsx should be unique for each logged-in user. I have successfully implemented the thread liking functionality in my app, but I encountered a hydration error, ...

What are the steps for setting up an Angular 2 library project?

Is the information provided in this article still applicable to the latest Angular 2 release, especially regarding module imports and exports? Are there any specific boilerplate templates available for this purpose? ...

I am encountering an issue where I am unable to locate the module 'http' or its associated type declarations when attempting to include ytdl-core

After downloading ytdl-core for my Angular project using npm install ytdl-core --save (https://www.npmjs.com/package/ytdl-core), I tried to use the module by importing it like this: import ytdl from 'ytdl-core'; ytdl(url); However, when I launc ...

Changing the background color of .pane and .view elements in an Ionic web application using JavaScript

Looking to modify the background-color of two css selectors, .pane and .view, that are located within the ionic.css file. Despite multiple attempts to do so using JavaScript directly in the index.html file, the changes are not reflected. The code snippet ...

How can I prevent IE10/IE11 from displaying the open or save prompt?

Currently, I am utilizing JavaScript blob to download files from the server as shown below: let blob = new Blob([resposne['_body']], { type: contentType }); if (navigator.msSaveBlob) { navigator.msSaveOrOpenBlob(blob, fileName); // applicabl ...

Strings and String enums do not align with each other

I am encountering a situation where I define the following type: export type BunionLevel = 'foo' | 'bar' | 'baz'; following it up with a class declaration like this: export class BunionLogger { level: BunionLevel; con ...

How to import an HTML file using TypeScript

I need to load an html file located in the same directory as the typescript file and return it from the function. public ...(... ) : angular.IHttpPromise<string> { ... return $http({ method: 'GET', url: &apos ...

Common problems encountered post Typescript compilation

I encountered the same problem. Below is my tsconfig settings: "compilerOptions": { "module": "commonjs", "moduleResolution": "node", "newLine": "LF", &q ...

Angular - Jest can manage the importing of the main entry point

Currently, I am attempting to create a simple test for a component that utilizes rete.js. However, the test is failing due to difficulty handling one of the required import paths. Component import { Component, ElementRef, Injector, ViewChild } from ' ...

"Encountering an unexpected error when Dockerizing an Angular App on Win10 Professional: EXPAND-ARCHIVE instruction not

I need to create a docker image for an Angular web application and deploy it on a Windows machine. However, I'm running into an issue when executing the command: docker build -t node . The following exception is thrown: Error response from daemon: ...