Troubleshooting the unexpected behavior of the shareReply() method in Angular version 15

Utilizing the same API across 3 components can lead to duplicate HTTP calls. To prevent this, I decided to cache the response using shareReply() from RxJs so it can be reused wherever needed. Here's how I implemented it:

api-service.ts

getUsers(): Observable<any> {
    let headers = new HttpHeaders();
    headers = headers.set('app-id', '63b691428f53f6370fc9eed6');
    return this.http.get(this.url, { headers }).pipe(
      map((resp) => {
        return resp;
      }),
      shareReplay()
    );
  }

test1-component

data$!: Observable<any>;
  constructor(private api: ApiService) {}

  ngOnInit(): void {
    this.loadTest1Data();
  }

  loadTest1Data() {
    this.data$.subscribe({
      next: (response) => {
        console.log('Loading data for Component - 1', response);
      },
      error: (error) => {
        console.log('Error While Loading data for Component - 1', error);
      },
      complete: () => {
        console.log('Success');
      },
    });
  }

test2-component (test3-component also use the same code)

data$!: Observable<any>;
  constructor(private api: ApiService) {}

  ngOnInit(): void {
    this.loadTest2Data();
  }

  loadTest2Data() {
    this.data$.subscribe({
      next: (response) => {
        console.log('Loading data for Component - 2', response);
      },
      error: (error) => {
        console.log('Error While Loading data for Component - 2', error);
      },
      complete: () => {
        console.log('Success');
      },
    });
  }

A problem occurred: reproducing HERE - Stackblitz

Cannot read properties of undefined (reading 'subscribe')

Can anyone help me understand what went wrong and how to fix it? Is there an alternative approach available that does not involve third-party state management tools?

Thank you in advance for your assistance.

Answer №1

Make sure your test components are properly defining data$. If not, this.data$.subscribe will essentially be trying to subscribe to undefined, resulting in an error.

To address this in the test components, you can use:

@Input() data$: Observable<any> = of();

Then pass it in like so:

<app-test1 [data$]="data$"></app-test1>

Alternatively, a more common approach is:

<app-test1 [data]="data$ | async"></app-test1>

This way, the components receive the data directly and the AsyncPipe handles subscriptions and unsubscriptions.

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

Leveraging Mermaid for angular applications

As a newcomer to Mermaid, I am attempting to integrate it into my Angular project. Placing it in my HTML has proven successful. <script src="https://cdnjs.cloudflare.com/ajax/libs/mermaid/9.0.1/mermaid.min.js"></script> <div class="merma ...

What could be causing the 405 error in my post request?

While attempting to send a post request to Firebase through my Vue app, I keep encountering an error illustrated in this image. I have a webpack server running and the website is on localhost:8080. However, I also have a live version hosted on hostinger a ...

I find it strange that this warning message continues to pop up even though there is already a key prop assigned. It keeps saying: "Each child in a list should have a unique 'key'

As a newcomer to React, I find myself puzzled by the recurring appearance of this warning message: Warning: Each child in a list should have a unique "key" prop Even though there is already a key prop present on the element, why does this warn ...

Checking radios or checkboxes will always result in a null value when retrieving their form values

After following the instructions in the Angular 2 cookbook for dynamic forms, I encountered an issue with the radios and checkboxes. Despite checking them, they always return a null value. Interestingly, the touched properties of the radios and checkboxes ...

Unable to properly test the functionality of the material-ui select component due to an error being thrown stating that the function is not being called

I've been utilizing the material-ui select component in my project and am currently writing tests for it. However, I've encountered an issue regarding testing the onChange event of the component. Here's a snippet of the code for my component ...

The function useNuxtApp() in Nuxt 3 is returning an unknown type

I have been working on creating a helper that can be used across all composables and applications in my Nuxt plugin. Here is how the code looks: // hello.ts export default defineNuxtPlugin(async nuxtApp => { nuxtApp.vueApp.provide('hello', ...

Tips for sending a string from the state of a React component to an external Python script

My journey into ReactJS and web development is just beginning. I am currently working on a web application where users can input mathematical expressions as strings. Upon submitting the input, I intend to process it using a Python script and display the o ...

Can jq handle synchronous functions?

The usage of jq.run('.', '/path/to/file.json').then(console.log) appears to be causing asynchronous behavior, leading to the output being displayed as Promise { <pending> }. This delay in obtaining the result is problematic, promp ...

React component will automatically rerender if the cache is disabled in the Chrome browser

In my React application, I am utilizing 'react-image-pan-zoom-rotate' to display images. Visit the GitHub repository here The image I am displaying is sourced from an external service and passed to both libraries for rendering. Lately, I have ...

I am encountering difficulty loading a .gltf file for use with Three.js on my React website

I uploaded my .gltf file of a 3D model to the public folder of my project and then ran the command "npx gltfjsx filename" to convert it into a .js React component. Within that .js file, I included the following line: const { nodes, materials } = useGLTF(&a ...

Looking for a dynamic solution to retrieve over 100 data products in Angular JS? Let's explore methods to efficiently call a large volume of

Just starting out with Angular JS and working on creating a searchable product list gallery using Angular JS. Currently, all my product data is in the same js file which I know isn't the best solution. I would like to make it dynamic by connecting to ...

How to fix the jquery error "Uncaught TypeError: Cannot read property 'style' of null" in an elegant way?

In my HTML code, I created a div element. When a user clicks a button, I run a simple JavaScript script to try to hide it: document.getElementById("samplques").style.display = "none"; However, I encounter an error when I execute the script: cannot rea ...

Disable the full screen camera mode on iOS browsers while live streaming camera video

I recently completed a tutorial on capturing video streams from the front or rear camera of an iPhone using JavaScript. The tutorial can be found at this link. While testing the functionality on my desktop browser, everything worked perfectly. However, wh ...

Ajax request experiencing 500 Internal Server Error. Uncertain about the source of the issue

I'm encountering a 500 Internal Server Error and I'm struggling to pinpoint the root cause of the issue. The purpose of this request is to delete a comment with a specific id from the database. The id is passed through a hidden input field. Below ...

Discover an Element within a JSON Array and Append a New Value to it

I've got an array of JSON data structured like this: [ { id: 1, name: 'Alice' }, { id: 2, name: 'Bob' }, { id: 3, name: 'Eve' } ] My goal is to locate an object by its id and append a ...

Ways to display a specific HTML element or tag depending on the given prop in VueJs

When working with Vue.js, it's important to remember that a <template> can only have one root element. But what should be done if you need to render different html elements based on a prop? For instance, let's say we have a <heading> ...

Use Jquery to select the checkbox inside the td element and mark it as

I've created an HTML table with checkboxes in the td elements, like so: <table id="my_table"> <tr> <td><input type="checkbox" name="td1"></td> <td><input type="checkbox" name="td2"></td> </ ...

Exploring the Depths with a Javascript Canvas Deep Zoom Library

I am faced with the task of creating a detailed zoom mosaic using an HTML5 Canvas Element, consisting of thousands of roughly 512x512 images. However, I am striving to minimize reinventing the wheel in the process. Instead of merging numerous large images ...

Invoke the API when the value of a property in the SPFX property pane is modified

Here's a question that might sound silly, but I'll ask anyway. I have a dropdown field in my Property pane that is filled with all the lists from the current site. It's working fine. When I change the dropdown selection, it populates a pro ...

Display the column every time the user types something into the search bar

Currently working on an Angular project and I'm trying to figure out how to make the middle column visible whenever the user enters text in the search bar. At the moment, I have a search bar for user input and three flex columns. The middle column is ...