Struggling to fetch Interval data accurately with Angular version 2 and above

Presenting dynamic data in a table generated based on the selections made in multiple drop-down menus. The second drop-down options are dependent on the first selection, followed by table generation reflecting these choices. To keep the table updated every 30 seconds, I previously used setInterval():

return Observable.interval(30000).flatMap(()=>{ 
  return this.http.get(url + data+'/userid='+ param).map(res => { 
     return res.json(); 
  }); 
)};

import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/mergeMap`;

The code functions as intended but encounters an issue where selecting a value in the second drop-down retains previous values and all drop-down options. Moreover, if dropdown options are 1,2,3 with 2 selected, refreshing at 30-second intervals displays values for 1 and 3 alongside the chosen value.

Answer №1

With the limited information provided, it seems like a question can be formulated from it. Some elements will need to be adjusted accordingly to provide an answer.

Key Points to Understand:

  1. Subject: An observable object that can emit by using onNext(...).
  2. switchMap: Mapping to an observable, completing the previous inner observable, and emitting values.

The process involves creating two subjects that emit values when users select options.

let firstValue$ = new Subject();
function on1stDropdownChanged(newFirstValue) {
    firstValue$.next(newFirstValue);
}
let secondValue$ = new Subject();
function on2ndDropdownChanged(newSecondValue) {
    secondValue$.next(newSecondValue);
}

A function is implemented to return necessary data based on the passed values:

function getUserData(firstValue, secondValue): Observable<UserData[]> {
    //Handle cases as needed.
    if (firstValue == undefined || secondValue == undefined)
    return Observable.of([]); //return empty results
    return ....
}

Another function returns second dropdown options based on the first value passed:

function getSecondValues(firstValue): Observable<SecondValue[]> {
    //Handle cases as needed.
    if (firstValue == undefined) 
    return Observable.of([]); //return empty results
    return ....
}

Two types of events are required:

  1. Selection of the 2nd dropdown.
  2. Fetching values when dropdown changes, then every 30 seconds thereafter.

An observable is created to emit when both the 1st and 2nd values are selected, followed by some adjustments:

let when2ndSelected = firstValue$.switchMap( //When 1st selected, wait for below 
    firstValue =>
        getSecondValues(firstValue) // get second options based on first.
            .do(secondValues=>...) //Action with second values
            .switchMap(_ => secondValue$) // Wait for 2nd selection
            .map(secondValue=>[firstValue,secondValue]) // map to array of first and second values
)

Subsequently, user fetching logic is implemented:

let timer = Observable.timer(0, 30000) // emit at 0,30,60sec ... 
let finalData$ = when2ndSelected
    .switchMap(firstSecondValue =>
        timer.switchMap(_time => getUserData(firstSecondValue[0], firstSecondValue[1])) //fetch new request every 30 seconds
    )

This serves as an approach to the problem, which may require customization based on specific needs. However, the overall functionality should remain intact.

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

What could be the reason for SVGR not producing a TypeScript declaration file in my esbuild setup?

I have been working on developing a custom SVG icon library using TypeScript. So far, the SVGR tool has been quite useful in creating components from SVG imports. However, I am encountering an issue with generating types that would allow me to pass attribu ...

Angular project models

I'm exploring the Core/Shared/Feature design pattern for building large, scalable applications in Angular, and I find myself unsure about where models fit in. Is there a consensus on which module they belong in? I came across a post suggesting that ...

Upgrade from RxJS 4 to RxJS 6

How can I convert this Rxjs 4 code snippet to Rxjs 6? const click$ = Rx.Observable.fromEvent($('.btn'), 'click').share(); click$ .scan((a, b) => a + 1, 0) .bufferTime(4000, null, 3) .filter(buffer => buffer.length > 0) ...

The transition from Angular 8 universal to the 9 Universal Version encountered a setback: the function require.resolve is not recognized

https://i.sstatic.net/IeLyV.png After delving into angular-errors, I stumbled upon the following error: [error] TypeError: require.resolve is not a function at SchematicImpl.<anonymous> (E:\B2C-NG-9\b2c\node_modules\@ngu ...

The attribute 'Error' is not available for the object of type 'MovieData | ResponseError'. This attribute is also not present in objects of type 'MovieData'

Question Answered I am currently working with two interfaces, MovieData and ResponseError. export interface MovieData { Poster: string; Title: string; Plot: string; imdbID: string; } The ResponseError interface looks like this: export interface R ...

There seems to be an issue with the validation feature in FormBuilder

I am currently working on a form that utilizes the FormBuilder. The challenge I am facing is displaying my custom validation message below the input field. While my code successfully shows a red "wrong" text when the input field is empty, it does not disp ...

Linking a string value to a specific data structure in TypeScript

I'm currently exploring typescript and I have a question about mapping a string value to a custom type when using templates in function calls. For instance: object.method<TypeMapper['CustomType']>([...]) In this scenario, 'Cust ...

Utilizing AngularJS2 with PHP on Apache server

Starting my journey with AngularJS today. Following tutorials on AngularJS version 2 using JavaScript. Node.js is a requirement, but my current development environment includes PHP, MySQL, and Apache (Xampp). I am curious if it is possible to develop and ...

Typedoc: only export contents from a particular file are documented

Currently, I am working on developing two npm packages: https://github.com/euberdeveloper/mongo-scanner https://github.com/euberdeveloper/mongo-cleaner My goal is to create documentation for these packages using Typedoc. The main file is index.js p ...

Check if a value is present in the array with *ngIf

I'm curious about how to use the ngIf directive in a specific scenario. In my Angular application, I have dynamically generated angular material toggles, each with a unique id. I'm familiar with using ngIf to conditionally display elements on the ...

At runtime, the array inexplicably becomes null

Having recently ventured into the world of Ionic framework development, I have encountered a puzzling issue. At runtime, an array inexplicably gets nulled and I am struggling to pinpoint the root cause. export interface Days { name:string; } @Compon ...

The comparison operator '===' is not suitable for comparing a number and a string when applied within [ngClass]

Is there a way for a div to have a css-class based on a specific value of the variable cfgSelected, in this case '1' (as a string)? <div [ngClass]="(cfgSelected ==='1')?'isActive':'isNormal'" (click)="selec ...

Testing an Angular 2 application that utilizes the jQuery library can be achieved by following these

I am currently working with Angular2 components that encapsulate a jQuery library called TimelineJS3. Everything is functioning correctly, but now I need to write tests. Specifically, I am trying to listen for click events using Renderer2. However, I have ...

Angular8's NgFor directive is designed to bind to Iterables like Arrays only

Having an issue retrieving data from Github and displaying it, as I am encountering errors. The code editor is highlighting an error with "followers" in the github-followers.component.ts file. githup-followers.component.html <div *ngFor="let follower ...

Unexpected behavior in resolving modules with Babel (using node and typescript)

Within my node project setup, I utilize babel-plugin-module-resolver for managing relative paths efficiently. tsconfig.json { "compilerOptions": { "outDir": "build", "target": "es5", ...

Learn how to merge two objects and return the resulting object using TypeScript functions within the Palantir platform

I am looking to generate a pivot table by combining data from two objects using TypeScript functions. My plan is to first join the two objects, create a unified object, and then perform groupBy operations along with aggregate functions like sum and min on ...

Attempting to connect to "http://localhost:4242/webhook" was unsuccessful due to a connection refusal when trying to dial tcp 127.0.0.1:4242

In my next.js 13 project, I am integrating stripe with TypeScript and configuring the app router. To create a stripe event in my local machine, I ran stripe listen --forward-to localhost:4242/webhook, but now I am encountered with the error message stripe ...

Exploring the depths of TypeScript's intricate type validation

Could you please review the comments in the code? I am trying to determine if it is feasible to achieve what I need or if TypeScript does not support such functionality. I require type checks for my addToRegistry function. Play around with TypeScript in ...

Angular 4 error: Property 'XX' does not exist in the type '{xx, xx}'

As a newcomer to this particular type of scripting, I have developed a model class which looks like this: export class Project { constructor( public projectId: number, public description: string, public startDate: Date, ...

Eliminating every instance of the character `^` from a given string

I am encountering an issue with a particular string: "^My Name Is Robert.^". I am looking to remove the occurrences of ^ from this string. I attempted using the replace method as follows: replyText.replace(/^/g, ''); Unfortunately, thi ...