Creating a real-time search feature with dual streams of terms in Angular 2

After diving into the Angular 2 documentation, I was able to grasp how to implement a live search feature using just one term as a parameter.

private searchTermStream = new Subject<string>();
search(term: string) { this.searchTermStream.next(term); }
items: Observable<string[]> = this.searchTermStream
  .debounceTime(300)
  .distinctUntilChanged()
  .switchMap((term: string) => this.wikipediaService.search(term));

Now, my goal is to extend this functionality by creating a live search for Restaurants with two parameters. I have already set up a Restaurant webservice that accepts both a term and region as parameters, and it will provide me with a list of available Restaurants based on those criteria.

Answer №1

Utilize the combineLatest() method in order to generate an Observable that combines the most recent values from two original observables.

private termObservable = new Subject<string>();
private regionObservable = new Subject<string>();
private criteriaObservable = 
    Observable.combineLatest(this.termObservable, 
                             this.regionObservable, 
                             (term, region) => {term, region});

Following that same approach demonstrated in your query, leverage the criteriaObservable to execute the search functionality. The function provided to switchMap() will accept an object containing the latest entered term and region.

Remember to supply a comparison function to distinctUntilChanged(), as it utilizes === for value comparisons by default, but you need tuples of term/region to be considered equivalent only when both terms and regions match:

items: Observable<string[]> = this.criteriaObservable
  .debounceTime(300)
  .distinctUntilChanged((o1, o2) => o1.term === o2.term && o1.region === o2.region)
  .switchMap(criteria => this.restaurantService.search(criteria.term, criteria.region));

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

Connecting data in Service with data in Controller

I am attempting to establish data bindings between a controller and a service. My goal is for the variable userIsConnected within my controller to update whenever the function getUserIsConnected returns a different value. Should I consider adding an attrib ...

Communication between components through a shared service

Imagine you find yourself in one component and need to trigger a method from another component. There are multiple ways to achieve this, which are explained in more detail on this page. Here, I will demonstrate the simplest possible example of how to make ...

Dependencies between libraries within a workspace

Recently, I set up a brand new Angular 6 workspace that includes an application along with two libraries: library1 and library2. library2 depends on a module from library1, as shown below import {Library1Module} from "library1" I successfully compiled li ...

"Employing Angular's UI Router for seamless navigation through a Multi-Step Form with thorough

I am currently using UI router and below is the configuration: state('app.requistion', { url: "/requisition", templateUrl: 'order/customer-skills/tmpl/main_requisition.html', title: 'Requisition', ...

Troubleshooting Angular: Investigating why a component is failing to redirect to a different route

I am currently implementing a redirect to a new route upon logging in using the following code: this.router.navigate(['/firstPage']); Oddly enough, when my application is initially loaded, this redirection does not occur automatically after logi ...

Issues with data binding not being correctly passed to the controller function parameter within the ng-repeat loop

I am in the process of creating a menu that allows users to adjust the CSS on my web application. Within my JavaScript method, I take a string input and then insert it into a URI for a bootswatch CDN. The code functions properly when I manually enter a str ...

Angular: determining if the current route or page is secured by a guard

I am currently working with Angular 9 and I was wondering if there is a way to determine if the current page is protected or guarded during the APP_INITIALIZER phase. Within my APP_INITIALIZER setup, I need to be able to identify whether the route being a ...

Updating a component without refreshing the entire page in Angular can be done by utilizing Angular's capabilities

I'm currently developing a project where I need to display a list of events and provide the option to filter events by week or month. How can I dynamically change the content on the page when the user clicks on the "Events by Week" button without havi ...

Guide to typing a new version of a function without any optional parameters using a mapped tuple

I am attempting to create a modified version of a function that has the same arguments as the original function, but with none being optional. I have tried using a mapped tuple approach with the following logic: type IFArgs = ArgsN<typeof getFunc> t ...

What is preventing Typescript from utilizing the includes function for arrays?

I understand that Typescript is based on ES6 or ES2015. However, I'm confused because anArray.includes('ifExist'); is only available in ES6. Even though I'm using Typescript, why am I unable to use it? The error message says that anAr ...

A guide on implementing RxJS Observables to target a specific DIV element

Currently, I am working with Angular 2. At the moment, I have been using this method to select a specific DIV element: <div #aaa> </div> @ViewChild('aaa') private aaa: ElementRef; ngAfterViewInit() { let item = this.aaa.nativeEle ...

"Troubleshooting: Custom AngularJS service controller encounters undefined error when accessing Custom Class Collection

I've been facing a peculiar issue while trying to incorporate AngularJS with ASP.NET MVC. I have used $http.get() to request a List of Custom Class Question, but it keeps encountering errors in the angular controller. Surprisingly, when I return List ...

DiscordJS bot using Typescript experiences audio playback issues that halt after a short period of time

I am currently experiencing difficulties with playing audio through a discord bot that I created. The bot is designed to download a song from YouTube using ytdl-core and then play it, but for some reason, the song stops after a few seconds of playing. Bel ...

Strategies for addressing input range slider cross browser compatibility issues

I have encountered an issue with the slider track while using a customized range slider with CSS. For Mozilla, I utilized the selector for progress (-moz-range-progress) and for IE I used -ms-filler-lower and -ms-filler-upper. Although it works well for b ...

What are the steps to limit the usage of angular.module('myApp', ['ngGrid', 'ui.bootstrap', 'kendo.directives'])?

I have two JavaScript files with AngularJS code. The first file, myjs1.js, includes the module: angular.module('myApp', [ 'ngGrid', 'ui.bootstrap', 'kendo.directives' ]); The second file, myjs2.js, also includes th ...

I am interested in utilizing the image.onload method within the $.when function

I am trying to dynamically load images inside a loop with specific requirements. In the code below, I want the alert to fire only when an image is being loaded, and then another alert to fire only after the first alert has fired. Here is my code: for (i ...

What is the correct way to include an NPM package in a Plunker project?

Encountered an error while utilizing angular2-infinite-scroll. Attempting to replicate it in a plunkr. Experimented with using npmcdn, hence added this line in the index.html file: <script src="https://npmcdn.com/<a href="/cdn-cgi/l/email-protectio ...

JSON parsing error: Found an unexpected token at character position 43

Attempting to retrieve data from a PHP Server that is running MySQL. Within my angular controller, I utilize $http.get("dbconnection.php") Inside the dbconnection.php file, the code simply selects all entries from the database and returns them. $conn = n ...

Utilize nodemailer in Angular 6 to effortlessly send emails

I am currently experiencing an issue with my email service form in my Angular 6 application integrated with Node.js. I have set up the form using Bootstrap and Nodemailer for sending emails, but it seems to not be working as expected. Whenever I attempt to ...

Fill an array with data and then implement a $watch function to update the list view in AngularJS

Below is a snippet of code from my controller: (function () { "use strict"; angular.module("app") .controller("postsController", postsController); function postsController($scope, $http, $uibModal, PostService) { var vm = this; $scope.p ...