Utilizing the async pipe with an RxJS interval on a component that is dynamically generated: A step-by

Is it possible to use the async pipe with RxJS interval() on dynamically created components, as shown in this example? When applying the async pipe inside the component, the interval is often ignored when components change.

For instance, if I want to retrieve data every 15 minutes but the components are changing every 15 seconds.

The only solution I've come across is to take data from one Observable and save it to another, but I'm not sure if this is the best practice. Is there a better way to achieve this?

The structure of the Observable is:

interval(1000 * 60 * 15).pipe(startWith(0), switchMap(() => this.http.get('someUrl')));

Solution that has worked for me:

interval(1000 * 60 * 15).pipe(startWith(0), switchMap(() => this.http.get('someUrl'))).subscribe((data) => {
  this.someUrlData = scheduled([data], asapScheduler);
});

Answer №1

Your proposed solution seems effective and acceptable, but it may be confusing for new developers without sufficient comments. In order to prevent potential misunderstandings or risky refactoring attempts, I would recommend a more clear and readable approach:

getData = new Subject<void>();

// UI Observable (used with async pipe)
someData$ = this.getData.pipe(
    switchMap(() => this.http.get('someUrl')),
    shareReplay(1)
)

// Subscriptions (in ngOnInit)
timer(0, 1000 * 60 * 15).subscribe(() => this.getData.next())

This approach offers better readability and provides control over data retrieval operations. Additionally, you can easily incorporate a "refresh" button by triggering the getData subject.

Remember to properly unsubscribe from the timer subscription to avoid memory leaks.


Update:

In response to your initial query, it is indeed considered a best practice to transfer values between Observables. To ensure continuity even when the component is destroyed, it is recommended to encapsulate such functionality within a service.

Answer №2

In my opinion, the solution you discovered is the most effective way to achieve your goal. By establishing a shared state with the interval time and checking it when creating the dynamic component, you can make the necessary HTTP call. It seems essential to have an outer state that can be monitored since the interval needs to be destroyed each time a new component is created.

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

You must include the formControlName within a parent formGroup directive

Upon creating a model-driven form, an error is encountered: Error: formControlName must be used with a parent formGroup directive. You'll want to add a formGroup directive and pass it an existing FormGroup instance (you can create one in your class). ...

What sets apart the commands npm install --force and npm install --legacy-peer-deps from each other?

I'm encountering an issue while trying to set up node_modules for a project using npm install. Unfortunately, the process is failing. Error Log: npm ERR! code ERESOLVE npm ERR! ERESOLVE unable to resolve dependency tree npm ERR! npm ERR! While resolv ...

Is it possible to multitask within a structural directive by performing two actions simultaneously?

I want to develop a custom structural directive with the following behavior: <p *myDirective="condition">This is some text</p> If condition is false, the <p> tag will not be displayed at all. If condition is true, the <p> tag wi ...

Whoops! Looks like there was a hiccup with the Vercel Deployment Edge Function, causing an

Every time I attempt to send a POST request to my Edge Function on Vercel Deployment, I encounter the following error message: [POST] /api/openai reason=EDGE_FUNCTION_INVOCATION_FAILED, status=500, user_error=true TypeError: Illegal invocation at app/api/ ...

Angular sets the required property only when the button is clicked

Is there a way to make a field required in Angular only when a button is clicked? Currently, the error message appears even before the user interacts with the field. I would like the error message "folder name is required" to only appear when the user cli ...

Ionic 2 faced an unresolved core-js dependency issue

Recently, I started working on a new Ionic 2 project and encountered an issue when trying to incorporate https://github.com/afrad/angular2-websocket. Upon installation, I received the warning message: UNMET PEER DEPENDENCY core-js@^2.4.1 The template pro ...

Encountering a Vueify Typescript error in a Vue project

Recently diving into the world of Vue, I was able to successfully create a sample app using gulp, vueify, and TypeScript. To showcase what's happening and shed light on an issue I'm facing, here are snippets of the key code segments: Menu.ts im ...

Ways to solve VScode gutter indicator glitches after switching text editors?

When my active function is running, I have a specific updateTrigger that ensures certain actions are taken when the activeTextEditor in vscode changes: const updateTrigger = () => { if (vscode.window.activeTextEditor) { updateDecorations(con ...

Efficient method for binding a select element when loading options is time-consuming

I am working with a select element within a custom component that retrieves a large number of options from a database and binds the options in the following manner: <select [id]="id" class="form-control" [formControlName]="id&qu ...

Setting default values in Angular dropdown select using TypeScript

How can a default value be set in a Select element? I am attempting to create a time dropdown select with multiple options. Currently, the selectedTimeOption variable correctly identifies if an option is chosen from the dropdown, but it cannot detect a va ...

How to extract a single value from ngFor in Angular 2

Currently, I am handling deep nested JSON objects from the server and using a pipe for parsing. However, the issue is that it is iterating through every key when I only need to retrieve one value. How can I accomplish this? Below are the relevant code sn ...

Tips for presenting SVG symbols using Interpolation within Angular 7 from a JSON document

When it comes to displaying content in Angular 7 components, JSON is used. However, I have encountered a problem while trying to incorporate SVG icons from our UX team into the component using JSON. Using the img tag restricts me from applying a CSS class ...

Unable to locate a type definition file for module 'vue-xxx'

I keep encountering an error whenever I attempt to add a 3rd party Vue.js library to my project: Could not find a declaration file for module 'vue-xxx' Libraries like 'vue-treeselect', 'vue-select', and 'vue-multiselect ...

Switch from using getElementById to useRef in React components

There is a requirement to update a functional component that currently uses getElementById to instead utilize the useRef hook. The original code snippet is as follows: import React, { useState, useEffect, useRef } from 'react'; import { createPo ...

Encountering the error message "TypeError: Unable to access properties of null (reading 'get')" while utilizing useSearchParams within a Storybook file

Looking at the Next.js code in my component, I have the following: import { useSearchParams } from 'next/navigation'; const searchParams = useSearchParams(); const currentPage = parseInt(searchParams.get('page') || '', 10) || ...

Struggling to compile TypeScript code

After updating TypeScript and NodeJS to the latest versions, I decided to test a simple TypeScript example by compiling it using both Node terminal and Windows 10 command line. Here is the code snippet I used: let greeting:string = "Hello!"; console.log(g ...

Adding a dynamic CSS stylesheet at runtime with the power of Angular and Ionic 2

Currently, I am working on creating a bilingual application using Ionic2. The two languages supported are English and Arabic. As part of this project, I have created separate CSS files for each language - english.css and arabic.css. In order to switch be ...

What is the way to assign a variable to ngClass in Angular?

I'm currently working on creating modals that will display different content based on which button is clicked. Each button should trigger a unique modal to appear, each with its own specific content inside. When a button is clicked, the 'active&a ...

Implementing a ReactJS component with a TypeScript interface for displaying an Alert box message using Material

I have a MUI Alert box in my application where I am trying to change the message inside with an href URL. However, when I use the herf tag, it shows as text instead of a link. How can I make it display as an actual link? In the code below, when I click th ...

Avoiding the occurrence of routing errors when an error arises in Angular 2

I've observed that whenever an error occurs in my Angular 2 application, it also disrupts the routing. Is there a method to address this and avoid the issue of breaking routing? ...