Tips for creating an API URL request with two search terms using Angular and TypeScript

I have developed a MapQuest API application that includes two input boxes - one for the "from" location and another for the "to" location for navigation. Currently, I have hardcoded the values for these locations in my app.component file, which retrieves the JSON data correctly. However, I am facing challenges in integrating these two distinct search boxes into my pipe using the current method. Below are the input boxes defined in the HTML:

<form >
         <input #from id="from"
            (keyup)="search(from.value)"/>

            <input #to id="to"
            (keyup)="search2(to.value)"/>
  </form>

And here is the TypeScript code snippet:

export class AppComponent implements OnInit {
  title = 'hw5-part1';
  mapResult: any;
  to: string = 'boston';
  from: string = 'poughkeepsie';

  private searchTerms: Subject<string>;

Any assistance on this matter would be greatly appreciated.
  constructor(private mapQuestService: MapQuestService) {  }

  search(term: string): void {
    this.searchTerms.next(term); }





  ngOnInit() {

    this.searchTerms = new Subject<string>();
    this.searchTerms.pipe(
        debounceTime(1000),
        distinctUntilChanged(),
        switchMap((x) => {
          console.log('the term is ', x)
          console.log(this.from, this.to);
          return this.mapQuestService.getMap(this.from, this.to);

        }))
      .subscribe((result: any) => {
        console.log(result);
        this.mapResult = result.items;
        console.log(result.route.legs[0].maneuvers);
      });
    }
}

Answer №1

To enhance the functionality, consider encapsulating the two values within an object before passing them to the switchMap() function.

this.searchTerms$.next({ "from": this.from, "to": this.to });

Update the implementation of switchMap() to utilize these two values effectively.

searchTerms$.pipe(
  debounceTime(1000),
  distinctUntilChanged((p, q) => p.from === q.from && p.to === q.to),
  switchMap(input => {
    let from = input.from;
    let to = input.to;

    if (from && to) {
      return this.mapQuestService.getMap(from, to);
    } else {
      return of([]);
    }
  })
);

Experience it firsthand on StackBlitz: https://stackblitz.com/edit/angular-two-values-in-switch-map

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

Preventing JavaScript Compilation for a Specific Folder using tsconfig: A Step-by-Step Guide

To create my own npx package, I'm currently working on converting my .ts files into .js. The purpose of the application is to generate TypeScript templates for users based on their selected options. In this app, there's a CLI called 'index.t ...

Unleashing the power of Angular 7+: Extracting data from a JSON array

As a newcomer to Angular and API integration, I am facing a challenge in fetching currency exchange rates data from the NBP Web API. The JSON file structure that I'm working with looks like: https://i.stack.imgur.com/kO0Cr.png After successfully ret ...

Tips for optimizing Angular source code to render HTML for better SEO performance

Our web platform utilizes Angular JS for the front-end and node js for the backend, creating dynamic pages. When inspecting the code by viewing the source, it appears like this: For our business to succeed, our website needs to be SEO-friendly in order to ...

Employing multiple subscriptions within a function

I am facing an issue in my Angular application where I am trying to display a detailed summary of the sales for a specific drink using the DrinkDetailComponent. However, upon initializing the component, only one backend call is being made to retrieve infor ...

Prohibit communication by any means

Let's take a look at the following function overloads: function f(key: undefined); function f(key: string | undefined, value: object | undefined); I want to allow calls with a single explicit undefined argument f(undefined), but require two argument ...

What allows the type expression to be considered valid with a reduced amount of arguments?

Currently diving into Typescript and focusing on functions in this unit. Check out the following code snippet: type FunctionTypeForArrMap = (value: number, index: number, arr: number[]) => number function map (arr: number[], cb: FunctionTypeForArr ...

Identifying Scroll Events with Ionic 2+ and Angular 2+: A Beginner's Guide

Is there a way to detect scrolling of the window? I attempted to use HostListener: @HostListener("window:scroll", []) onScroll() { console.log('scroll'); } I also experimented with using Renderer2: this.renderer.listen( 'window&apo ...

Guide to utilizing @types/node in a Node.js application

Currently, I am using VSCode on Ubuntu 16.04 for my project. The node project was set up with the following commands: npm init tsc --init Within this project, a new file named index.ts has been created. The intention is to utilize fs and readline to read ...

Can errors be selectively ignored in Angular's global error handler based on certain conditions?

I am currently facing a situation where I need to handle errors when calling an API to save data, either manually or automatically. For manual saves, I have implemented an Angular global error handler to display the error message if the save fails. Howeve ...

Developing a common module for use across deferred loading paths

I have been working on developing an Angular 11 application and am currently in the process of creating a SharedModule. My goal is to prevent loading common modules repeatedly across my lazy loaded routes. To achieve this, I created a shared module and imp ...

Transition from using ReactDOM.render in favor of asynchronous callback to utilize createRoot()

Is there a React 18 equivalent of this code available? How does it handle the asynchronous part? ReactDOM.render(chart, container, async () => { //code that styles some chart cells and adds cells to a worksheet via exceljs }) ...

What causes a double fill when assigning to a single cell in a 2-dimensional array in Javascript?

I stumbled upon this code snippet featured in a challenging Leetcode problem: function digArtifacts(n: number, artifacts: number[][], dig: number[][]): number { const land: boolean[][] = new Array(n).fill(new Array(n).fill(false)) console.log ...

Checking constructor arguments and code style issues

I need to ensure that the constructor parameter is validated correctly when an instance of a class is created. The parameter must be an object that contains exactly all the properties, with the appropriate types as specified in the class definition. If t ...

Unable to modify the border-radius property of Material UI DatePicker

I'm having difficulties setting rounded borders for my DatePicker component from @mui/x-date-pickers and Material UI V5. Here is the intended look I am aiming for: https://i.stack.imgur.com/c1T8b.png I've tried using styled components from Mat ...

The TypeScript error message indicates that a value typed as 'string | undefined' cannot be assigned to a type 'string'

In my TypeScript-based React application where I am utilizing material-ui for components, I am currently working on creating a wrapper for material-ui's input. Here is the code snippet: import FormControl, { FormControlProps } from "@material-ui/core ...

Elevating font-awesome from version 4.7 to 5.11.1 in an Angular 6 project

Currently in my angular 6 project, the parent module utilizes font-awesome 4.7 as shown in package.json; "font-awesome": "^4.7.0", and angular.json; "styles": ["projects/adminUI/src/styles.css", "./no ...

Webpack magic comments are not supported by dynamic import in Angular 8.0

After upgrading from Angular 7 to Angular 8, I observed a downgrade in my webpack version from 4.33.0 to 4.30.0. With the new support for dynamic importing in angular8, I wanted to utilize webpack "magic comments" to customize the chunk name of my angula ...

Access-Control-Allow-Methods is not permitting the use of the DELETE method in the preflight response for Angular 2

I am having trouble deleting a record in mongodb using mongoose. Here is the code snippet from my component: deleteProduct(product){ this._confirmationService.confirm({ message: 'Are you sure you want to delete the item?', ...

Issue with Angular 7 Universal: components inside are failing to display

I have successfully implemented Angular 7 Universal with dynamic server-side rendering. However, I am facing an issue where dynamic components within the main component being rendered on the server are not rendered themselves. Here is an example of the re ...

Access to this feature is restricted when using a decorator in TypeScript with NodeJS

I have designed a decorator to handle async errors, but I am encountering difficulties in accessing it within class methods. My goal is to develop a reusable CRUD class that other classes can inherit from, with a method for CRUD operations. Decorator Code ...