Managing the synchronization of a time-consuming method in Angular using TypeScript

We are currently utilizing TypeScript and Angular 6 in our development project and have a service class that is injectable:

@Injectable()
export class ProductService {
    getAllProducts(): Observable<Product[]> {
        return this.http.get('/products')
    }
}

Within our Angular application, there are three separate components nested deep within the structure that all require access to the product list.

Our goal is to enable each component to make use of:

this.productService.getAllProducts().subscribe(products => ...)

However, this approach initiates three distinct HTTP requests, along with client-side JSON parsing, which is not efficient.

One common solution would involve retrieving the Product[] data once at the outermost page and passing it down to each individual component. Yet, this method leads to cluttered code and increases the complexity of passing data down between components.

In a Java environment, I would simply synchronize access to the getAllProducts() method and cache the result within the ProductService, returning the cached data if available.

Is there a way to achieve a similar outcome in Angular/TypeScript that is both efficient and streamlined?

Answer №1

If you're searching for the RxJS share operator, you're in the right place.

  constructor(private httpClient: HttpClient){
    this.dataFromServer$ = this.httpClient.get<any[]>('https://jsonplaceholder.typicode.com/posts');
    this.sharedData$ = this.httpClient.get<any[]>('https://jsonplaceholder.typicode.com/posts/1').pipe(share()) 

    // Making 3 Requests
    this.dataFromServer$.subscribe()
    this.dataFromServer$.subscribe()
    this.dataFromServer$.subscribe()


    // Making 1 Request
    this.sharedData$.subscribe()
    this.sharedData$.subscribe()
    this.sharedData$.subscribe()
  }

https://stackblitz.com/edit/angular-zsw7zq?file=src%2Fapp%2Fapp.component.ts

Sometimes, considering shareReplay is advisable. Especially when the subscription occurs after the request is successful.

For more in-depth exploration, I suggest looking into the concepts of "angular hot / cold observable".

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

Comparison between a Typescript optional field and a field that has the potential to be undefined

Can you clarify the contrast between an optional field and a T | undefined field? export interface Example { property1: string | undefined property2?: string } ...

The service being injected is not defined

Two services are involved in this scenario, with the first service being injected into the second service like so: rule.service.ts @Injectable() export class RuleService { constructor( private _resourceService: ResourceService ){} s ...

Tips for transferring a variable from Next.js to a plain JavaScript file

When it comes to Canvas Dom operations in my NextJs file, I decided to include a Vanilla JS file using 'next/script'. The code for this is: <Script id="canvasJS" src="/lib/canvas.js" ></Script>. Everything seems to ...

Display the option to "Delete" the link only when there are multiple images in my image collection

I am using jQuery and Ajax to remove banner images from my website. However, I want to make sure that if there is only one image left, it cannot be deleted. Each image in the list has a corresponding delete link: echo '<a class="delete j_bannerd ...

Can a component be passed as props and utilized within a child Component in Vue.js?

If we have components A, B, and C in a Vue 2.0 app, A declares, registers, and uses B. Can we pass C from A to B? For example: <template> <div class="A"> <B :child_component="C" /> </div> </template ...

Using a vanilla JS object as a prop for a child component

I have created a custom Message class in my application to handle incoming messages, which is defined in message.js. Within message.js, I've implemented two classes: Message and EventEmit. The render function in my Message class requires passing an E ...

Browsing through tabs to locate specific text

Currently, I am developing a feature for a Chrome extension and I could use some assistance in debugging. The feature involves retrieving a user's input as a string from a text box on popup.html and then scanning through all the open tabs in the curr ...

Ways to showcase flair in PHP code such as this

I currently have this code snippet: <h2 class="index-single">Tech Categories</h2><?php $args2 = array( 'cat' => 11 , 'posts_per_page' => 9 , 'paged' => $paged ); $the_query2 = new WP_Query( $args2 ); ...

The code for populating the lookup does not perform as expected on the initial attempt

I've encountered an issue with my JavaScript code on a form where it auto populates 2 lookup fields with the current user when the record is being created. Most of the time, this function works as intended. However, I've noticed that during the f ...

What is the best way to notify administrator users when their accounts have exceeded the timeout period?

Working on the website for our high school newspaper, I've encountered a recurring issue on the admin page. Users are getting logged out after creating an article due to a time limit constraint. To address this problem, my goal is to implement an aler ...

The function react.default.memo is not recognized at the createSvgIcon error

After updating my Material-UI version to 1.0.0, I encountered a peculiar error message stating that _react.default.memo is not a function at createSvgIcon Despite attempting to downgrade the react redux library to version 6.0.0 as suggested by some ...

Sending a JavaScript value to PHP after a quiz has been completed

I've created a web page where users can take quizzes. These quizzes dynamically generate questions using JavaScript each time they are accessed. Disclaimer: I'm fairly new to JavaScript. Once the user completes the quiz, they receive their fina ...

What is the procedure for deactivating a plugin within the replace feature of CkEditor?

Is there a way to disable image-upload on specific CKEditor textareas without affecting all of them through the config.js file? I'm wondering if it's possible to achieve this using the .replace method. For example: CKEDITOR.replace("meTextarea" ...

There is only a singular font awesome icon that appears properly based on the conditions set by [ngClass

I'm currently developing a user profile feature that allows users to submit links to their social media accounts. Each account is represented by a clickable icon, and the selection of which icon to display is based on various conditions within [ngClas ...

The value of 'this.selectedNodes' does not support iteration and is causing a

I am currently utilizing v-network-graphs to generate graphs in the front end with Vue. I have set up my data like this: data(){ return{ test: test_data, nodes:{}, edges:{}, nextNodeIndex: Number, selectedNodes: ref<st ...

Issue with Vue directive bind not functioning after element refresh

My approach involves utilizing vue.js to create forms, where all fields are structured within a JavaScript objects array. Here is an example of the structure I use: { type: "input", mask: "date", default: "2018/04/14" }, { type: "input", ...

Ways to remove a dynamic field with jquery

I have developed a script that allows me to add dynamic fields and delete them as needed. However, I am facing an issue where I cannot delete the first element with the "el" class in my script because it removes all elements within the "input_fields_cont ...

Angular2 combined with redux fails to produce any outcomes

Currently, I am implementing redux in conjunction with angular2 and attempting to make a call to Windows Azure Search. Below is the snippet of code that I have written: types.ts export interface IAppState { languageState?: LanguageState; searchState? ...

tips and tricks for adding content to json with the help of jquery/javascript

Is it possible to include text in a JSON array using jQuery or Javascript? Assuming that there is data in the following format: A list of numerical codes stored in a text file as 123, 456, 789 I am looking to convert them into a JSON array using JavaScr ...

Divide a nested list into individual lists

I am working on a navigation menu with nested lists and I need to split the nested lists using jQuery while keeping the original headings intact. Can anyone help me achieve this? Below is the HTML code: <ul id="bigList"> <li><a href="#"& ...