angular 6's distinctUntilChanged() function is not producing the desired results

I have a function that retrieves an observable like so:

constructor(private _http: HttpClient) {}

getUsers(location){
   return this._http.get(`https://someurl?location=${location}`)
          .pipe(
              map((response: any) => response),
              distinctUntilChanged()
           )
}

(Assuming all required dependencies are imported)

To display the list of users, I use the loadUsers method.

loadUsers(location){
   this.getUsers(location).subscribe( users => {
       this.userList = users;
    });
}

ngOnInit(){
    this.loadUsers('mumbai');
}

The code above loads the list of users for those located in Mumbai.

Now on the UI, there is a list of locations with checkboxes next to them like:

Mumbai,
Delhi,
Kerala

Clicking on a location will trigger the loadUsers method with the selected location as a parameter.

When clicking on Mumbai again (without selecting any other location first), I don't want it to reload the Mumbai users since they were already loaded initially.

I've tried using distinctUntilChanged() but it doesn't prevent the unnecessary call when selecting Mumbai from the checkbox list.

Note: This scenario is fictional. I shared it to explain my issue clearly.

I'm new to Angular and RxJS. Any assistance would be appreciated.

Answer №1

Your code for ensuring that getUsers() is not invoked again for the same location can be improved by using distinctUntilChanged along with Observables. Modify your code to include a list of locations as an observable and push new locations into a Subject, allowing you to apply distinctUntilChanged on this input list.

const currentLocation = new Subject();
on('click', () => currentLocation.next(this.value)); // Triggered when location list items checkboxes are clicked

currentLocation.pipe(
  distinctUntilChanged(),
  mergeMap(location => loadUsers(location)
)
.subscribe(users => {
  this.userList = users;
});

This solution simplifies handling repeated calls to getUsers() for the same location in Angular applications. Remember, there may be additional boilerplate code necessary within the angular framework for full implementation.

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

Guide to importing a JavaScript module using jQuery

I have been encountering an issue while loading a javascript file using jquery. The code I am working with is as follows: // file application.js $.getScript("module.js", function(data, textStatus, jqxhr) { ... }); Everything seems fine so far. However, t ...

Variations between <div/> and <div></div>

When using Ajax to load two divs, I discovered an interesting difference in the way they are written. If I write them like this: <div id="informCandidacyId"/> <div id="idDivFiles"/> Although both divs are being loaded, only one view is added ...

Effect of Active or Focus on the HTML <ul> element

Check out this example of a UL tag: <ul style="list-style-type:none; padding:5px ; border:solid 1px #666666;"> <li>I am waiting </li> <li>I am waiting </li> <li>I am waiting </li> <li>I am wa ...

Incorporating imports disrupts the script configuration in Nuxtjs 3

Issues arise when utilizing the import statement within the context of <script setup>, causing subsequent code to malfunction. After installing the @heroicons package and importing it as a component in the <template>, all code below the import ...

Make sure link opens in the same window/tab

Currently, I am utilizing the Open Link in Same Tab extension on Google Chrome. This extension can be found here. The purpose of this extension is to ensure that all links open in the same window/tab, which is necessary for touch screen kiosk left/right s ...

Having trouble retrieving cookie in route.ts with NextJS

Recently, I encountered an issue while using the NextJS App Router. When attempting to retrieve the token from cookies in my api route, it seems to return nothing. /app/api/profile/route.ts import { NextResponse } from "next/server"; import { co ...

NextJS hot reload with Docker is a powerful combination for seamless development environments

I've encountered issues trying to configure hot reload with Docker and NextJS. When I make changes and save a file, the server does not reload. Below is the contents of the docker-compose.yml: version: '3' services: mainapp: build: ./ ...

In React conditional return, it is anticipated that there will be a property assignment

What is the optimal way to organize a conditional block that relies on the loggedIn status? I am encountering an issue with a Parsing error and unexpected token. Can someone help me identify what mistake I am making and suggest a more efficient approach? ...

Incorporate a distinct identifier for every menu item within the Material UI TablePagination

Can a unique identifier be assigned to each menu item generated using the <TablePagination> component? I would like to add a specific ID (e.g., id="menu_item_0", id="menu_item_1" & id="menu_item_2") to the menu item ...

In what way can a piped operator in rxjs be influenced by the value returned by a subsequent operator?

When attempting to examine values between operators in an rxjs pipe, I decided to use tap to log them to the console. I added two taps, one before a map operator used for sorting an Array, and one after. Surprisingly, both taps logged the same sorted Arra ...

Having difficulty accessing any of the links on the webpage

I'm currently utilizing the selenium webdriver to automate a specific webpage. However, I am encountering an issue where my selenium code is unable to identify a certain link, resulting in the following error message. Exception in thread "main" org ...

The legends on the Google chart are having trouble being displayed accurately

Take a look at the screenshot below to pinpoint the sample issue. While loading the graph UI with Google Charts, the legends data is showing up but not appearing correctly. This problem seems to occur more frequently on desktops than on laptops. Any advi ...

How do I repeatedly invoke a function in JQuery that accepts two different arguments each time?

I have a collection of folders, each containing various images. The number of pictures in each folder ranges from 8 to 200. Folders are numbered from 1 to 20 and the images within them are also labeled numerically. My goal is to aggregate all these images ...

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 ...

Conflicting Transformation Properties Causing CSS Issues Within a Single Element

I'm currently working on a user interface where users can drag and drop a box with a red outline to position it on the screen within a black box. See the UI here Alternatively, users can also move the box by adjusting the inputs on the right side. ...

Safari 11.1 and Angular 9 - config object missing a defined key-value

While using Safari, I have encountered a problem in the Primeng input text field. When I type into the text box, errors are logged into the console. handleKeypress — injected.entry.js:8231TypeError: undefined is not an object (evaluating 'settin ...

Could someone clarify for me why I am unable to view the connection status within this code?

Having trouble with the Ionic Network plugin. I've included this code snippet, but it's not functioning as expected. No console logs or error messages are showing up. import { Network } from '@ionic-native/network'; ionViewDidLoad() { ...

Tips for extracting the chosen value from a dropdown list within a table cell using JavaScript

Here is an example of an HTML element: <td> <select> <option value="Polygon 47">Polygon 47</option> <option value="Polygon 49">Polygon 49</option> </select> </td> I am looking for a ...

Attempting to sort data with AngularJS

I'm currently working on implementing 'order by' functionality in my Angular app. Here's what I've attempted: <div *ngFor = "let movie of webService.movie_list | async | orderBy:'Year'"> However, when testing it ...

Harness the power of React Material-UI with pure javascript styling

I am currently attempting to implement Material-UI in pure javascript without the use of babel, modules, jsx, or similar tools. <!DOCTYPE html> <html lang="en" xmlns="http://www.w3.org/1999/xhtml"> <head> <meta charset="utf-8 ...