Tips on triggering the subscribe function only when either the parameter or one key-value pair of the query parameter changes

In my current situation, I need to trigger the subscribe action only when either the parameters in the URL change or when showList changes in the query parameter. The rest of the query parameters like

page=0&size=5&sort=name,asc
are added for scenarios such as reloading the page or navigating back to the same URL. However, this leads to the subscribe action being fired twice after the addition of these parameters following the showList query parameter.

The route changes occur as follows: when the showList button is clicked,

http://localhost:8080/org/acount/param1/param2?showList=true
http://localhost:8080/org/acount/param1/param2?showList=true&page=0&size=5&sort=name,asc

The second navigation occurs because when showList is true, an API call is made to fetch the list of accounts and if the API returns a non-empty result, then page, size, and sort are set.

If the hide button is pressed, the route changes to:

http://localhost:8080/org/acount/param1/param2?showList=false

I also need to handle cases like reload and when the back button is pressed.

To address the above scenario, I have implemented the following solution, although I acknowledge that it may not be the most optimal approach:

this.params_subscribe = combineLatest([this.activatedRoute.params, this.activatedRoute.queryParams]).pipe(
      map(results => ({ param: results[0], query: results[1] }))
    ).subscribe(result => {
      let show_list: boolean = (result.query.showList === 'true');
      if ((JSON.stringify(result.param) !== JSON.stringify(this.prevParam)) || (result.query.showList !== this.prevQueryParam.showList)) {
        if (!this.from_ui || result.query.showList !== 'false') {
          if (result.param.teamId && result.param.breadcrumb) {
            ...
          }
          else {
            this.initialize()
          }
        }
      }
      this.prevParam = result.param;
      this.prevQueryParam = result.query;
    });

from_ui is utilized to prevent the function from being called if the query parameter has changed by clicking the hideList button which sets showList to false.

Is there a more effective way to handle this situation?

Answer №1

If you're looking to ensure uniqueness in your data stream, consider using the distinceUntilChanged operator alongside a custom comparator function.

Give this approach a try:

combineLatest([
  this.activatedRoute.params, 
  this.activatedRoute.queryParams
]).pipe(
  map(results => ({ param: results[0], query: results[1] })),
  distinctUntilChanged((prev, curr) =>
    JSON.stringify(prev.result.param) === JSON.stringify(curr.result.param) &&
    prev.result.query.showList === curr.result.query.showList
  )
).subscribe(
  ...
);

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

Error: Unable to access the 'push' property of an undefined variable in Ionic 3

I encountered an issue while attempting to redirect to a different page after a successful callback. The error message that I received was TypeError: Cannot read property 'push' of undefined this.http.post('http://localhost:3030/users&apos ...

What is the predetermined time limit for an HTTP GET request made using the HttpClient module in Angular 2?

I'm currently investigating the default timeout for an HTTP GET request made with HttpClient in Angular 2. I need to determine if the timeout is occurring at the endpoint due to a large query or if it's caused by the request itself timing out. Un ...

Exploring Angular: How to implement a listener to detect when data (such as a video) is loaded and trigger actions

I'm currently working on displaying a video in my Angular page and I'm trying to set the currentTime property of the video to start playing at a specific time. In JavaScript, you can achieve this with the following example: document.getElementBy ...

Issue TS2365: The operation of addition cannot be performed between an array of numbers and the value -1000

I'm encountering an error in my ng serve logs despite the function functioning properly with no issues. However, I am concerned as this may pose a problem when building for production. How can I resolve this error? uuidv4() { return ([1e7]+-1e3+- ...

Mongoose: An unexpected error has occurred

Recently, I developed an express app with a nested app called users using Typescript. The structure of my app.js file is as follows: ///<reference path='d.ts/DefinitelyTyped/node/node.d.ts' /> ///<reference path='d.ts/DefinitelyTyp ...

Angular Dropdown Menu: A Comprehensive Guide

Searching for a straightforward example on how to bind a dropdown menu? Many tutorials online suggest creating a separate component, but is that really practical for real-world applications? I need a simple language dropdown inside the login form where us ...

What is the best way to access a class's private static property in order to utilize it for testing purposes?

Hello, I am currently a beginner in TypeScript and unit testing, so this inquiry may seem elementary to those more experienced. I am attempting to perform unit testing on the code provided below using sinon. Specifically, I am interested in testing whethe ...

Encountered difficulty locating the webpack-subresource-integrity module following ng serve execution

I am new to Angular and recently attempted to install bootstrap, but encountered issues causing it not to work. Subsequently, I decided to uninstall it. However, when I ran the command ng serve, I received an error message stating An unhandled exception oc ...

Showing a ng2-pdf-viewer PDF contained within a stream

My webpage integrates the ng2-pdf-viewer library: <pdf-viewer [src]="fileToDownload" [render-text]="true" style="display: block;"></pdf-viewer> A Node API is used to fetch the PDF file and return a URL: this.httpC ...

Error encountered in Typescript React: JSON API Object expecting a ":" when indexing

Using Axios in Typescript React to fetch API Data. Here is a glimpse of the JSON Data :https://i.sstatic.net/DCXTz.png Trying to access the number value at index 1.tokenAmount.uiAmount Currently attempting data?[1]["tokenAmount"]["uiAmount"], but encoun ...

The clash between the definitions of identifiers in this file and another (@types/jasmine) is causing error TS6200

While trying to build my project with Angular CLI, I am encountering the following error message: ERROR in ../my-app/node_modules/@types/jasmine/index.d.ts(18,1): error TS6200: Definitions of the following identifiers conflict with those in another file: ...

I am facing difficulty in using Angular's ngIF directive with my object property for toggling visibility based on a condition

When writing a condition using *ngIf in my HTML code, I encountered an issue with displaying a mat-list-item based on an object property. Here is the code snippet: <mat-list-item *ngIf="object.conditionName" [ngClass]="((object.show) || i%2 != 0) ? ...

In TypeScript, enhancing an interface with additional properties

Currently, I am working on an Angular project and have developed this interface to display some data: export interface UserData { name: string, vorname: string, strasse: string, plz: string, ort: string, handynummer: string, telefonnummer: s ...

Node Sass was unable to locate a binding for the current environment you are using: OS X 64-bit running Node.js 12.x

Currently, I am encountering an issue while constructing an Angular project. The error message that I am facing is as follows: ERROR in Module build failed (from ./node_modules/sass-loader/lib/loader.js): Error: Missing binding /XXXXXXX/node_modules/nod ...

Integrating concealed elements into jspdf

I am currently working on incorporating a hidden div into my jspdf file. Utilizing html2canvas for this purpose, I find it necessary to briefly make the div visible, add it to the pdf, and then hide it again. This method is not ideal as the content moment ...

Rule Set Selector with Multiple Combo Box Options

In order to simplify the process, I have created a set of rules for a combo boy as follows: A | B 1 | 1 1 | 2 2 | 2 2 | 3 Columns A and B represent the values that can be selected in a combo box. For example, if the first combo box is set to value 1, then ...

Creating a new ES-6 class to extend express-js: Issues with binding getter and setter properties

I am intrigued by the idea of utilizing Express within an extended class. My goal is to create getter and setter methods for a property, but I'm facing the issue of these methods not being bound to the instances as desired. One way to work around this ...

Unraveling the Mystery of @Input and @Output Aliases in Angular 2

After researching about the @Input() and @Output() decorators, I discovered that we have the option to use an alias instead of the property name for these decorators. For example: class ProductImage { //Aliased @Input('myProduct') pro ...

The location of the Aurelia breakpoint needs adjusting

The issue I am encountering involves the aurelia skeleton-typescript-webpack project. When attempting to debug the TypeScript code in Chrome, the breakpoints do not align properly with where the program actually stops. Here's an example: After placin ...

Creating a type definition for the createSelector function based on the useQuery result

Struggling to find the correct typings for the createSelector res parameter from redux-js, especially in TypeScript where there are no examples or explanations available. The only guidance is provided in JS. const selectFacts = React.useMemo(() => { ...