The function switchMap does not exist in this context

After completing the Angular Tour of Heroes tutorial and some others, I decided to start building apps with Angular 2. One important thing I learned is that when we're listening for changes with a Subject, it's good practice to wait for a few seconds before making a request in order to avoid burdening the network.

Below is the code snippet I'm currently working on:

import { Injectable } from '@angular/core';
import {Http} from "@angular/http";
import {Observable} from "rxjs/Observable";
import 'rxjs/add/observable/of';
import 'rxjs/add/operator/catch';
import 'rxjs/add/operator/debounceTime';
import 'rxjs/add/operator/distinctUntilChanged';
import 'rxjs/add/operator/switchMap';
import {Employee} from "../employee";

@Injectable()
export class EmployeeSearchService {

  private getPersonalURL:string = 'api/employee';   // Using mock data for now

  constructor(private http:Http) { }

  search(term:string): Observable<Employee[]> {
    return this.http.get(`api/employee/?firstName=${term}`)
      .map(response =>  response.json().data as Employee[])
      .catch(this.handleError);
  }

  searchEmployees(term: Observable<string>): Observable<Employee[]> {
    return term.debounceTime(200)
       .distinctUntilChanged()
       .switchMap(term => this.search(term)); // Error occurs here
  }

  private handleError(error: any): Promise<any> {
    console.error('Error on EmployeeSearchService', error);
    return Promise.reject(error.message || error);
  }

}

And here's the component where the service is being called:

import { Component, OnInit } from '@angular/core';
import {Subject} from "rxjs/Subject";
import { EmployeeService } from '../employee.service';
import { Employee } from '../employee'
import {EmployeeSharedService} from "../employee-shared.service";
import {EmployeeSearchService} from "../employee-search/employee-search.service";

@Component({
  selector: 'employee-list',
  providers: [ EmployeeService ],
  templateUrl: './employee-list.component.html',
  styleUrls: ['./employee-list.component.css']
})
export class EmployeeListComponent implements OnInit {

  employees: Employee[];
  selectedEmployee: Employee;
  sortAsc: boolean;

  searchQuery = new Subject<string>();

  constructor(private employeeService:EmployeeService, private employeeSearchService:EmployeeSearchService, private employeeSharedService:EmployeeSharedService) {
    this.sortAsc = true;

  }

  ngOnInit() {    // Call initiated from here
    this.employeeSearchService.searchEmployees(this.searchQuery)
        .subscribe(result => {
          this.employees = result;
          if(!result) {
            this.getAllEmployees();
          }
        });
  }

  getAllEmployees(): void {
      // Function to retrieve all employees from the service
  }

}

The error message received is:

TypeError: term.debounceTime(...).distinctUntilChanged(...).switchMap is not a function

I'm wondering if there's something missing in my code, such as an import statement or something else? The code structure and imports are similar to those in the Angular Tour of Heroes tutorial which worked fine for me. Any insights would be appreciated!

Answer №1

Don't forget to include the switchMap operator:

import 'rxjs/add/operator/switchMap';

Answer №2

The suspect has been identified

searchQuery = new Subject<string>();

An Subject is definitely not an observable, however your function is requesting one, therefore it should be adjusted as follows

ngOnInit() {
    this.employeeSearchService.searchEmployees(this.searchQuery.asObservable())...
}

Answer №3

To utilize it, you must import switchMap from the rxjs library as follows:

import { switchMap } from 'rxjs';

Even though it was not automatically highlighted as being used, I explicitly referenced it in the code like so:

return this.user$ .rxjs.switchMap((user: firebase.User) => this.userService.get(user.uid));

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

A Step-by-Step Guide on Modifying the Default Button in Angular2CSV

I am currently utilizing Angular 4 along with the Angular2CSV plugin to transfer data from an Angular page to Microsoft Excel. The process has been successful thus far. However, I am interested in changing the name of the button but am unsure of how to d ...

Utilize Firebase to perform a case-insensitive query

Our Angular/Ionic app requires users to provide their email during registration, which is then saved in the User collection. We also validate if the email is already in use with a query like this: firestore .collection("User") .where("email", "==", ...

Guide on embedding child components in content using ngx-markdown within Angular version 14

I've been struggling to find a solution to this issue for some time now. We are receiving HTML content from an epi-server that needs to be dynamically rendered in a component. While ngx-markdown works well with standard HTML elements, it seems to ign ...

No recommended imports provided for React Testing Library within the VS Code environment

I am currently in the process of setting up a Next JS project with Typescript integration and utilizing React Testing Library. Unfortunately, I'm facing an issue with getting the recommended imports to work properly within my VS Code environment. To i ...

Is there a way to ensure that the onChange event of ionic-selectable is triggered twice?

I've been working with an ionic app that utilizes the ionic-selectable plugin, and for the most part, it's been running smoothly. However, I encountered a rare scenario where if a user on a slow device quickly clicks on a selection twice in succe ...

Implementing Styled API in TypeScript with props: A Comprehensive Guide

I'm currently working on styling a component using the new styled API, not to be confused with StyleComponents. const FixedWidthCell = styled(TableCell)((props: { width: number }) => ({ width: props.width || 20, textAlign: "center", })) The i ...

Is it possible to retrieve the second computed type in an overloaded method using TypeScript?

Looking for a solution to receive the second calculated type in an overload method using TypeScript type V1 = 'v1'; type V2 = 'v2'; type Versions = V1 | V2; async analyze(test: 'v1', data: number): Promise<void> ...

Unexpected behavior with HashLocationStrategy

I am currently tackling a project in Angular2 using TypeScript, and I seem to be having trouble with the HashLocationStrategy. Despite following the instructions on how to override the LocationStrategy as laid out here, I can't seem to get it to work ...

Error: The function createImageUrlBuilder from next_sanity__WEBPACK_IMPORTED_MODULE_0__ is not defined as a valid function

Having some trouble with my Next.js TypeScript project when integrating it with sanity.io. I keep getting an error saying that createImageUrlBuilder is not a function. See screenshot here Here is the code from my sanity module ...

How can I retrieve the /api/auth/me resource serverside using the NextJS AppRouter?

I am looking to implement app router in my Next.js project and have encountered an issue. In order for my app to function properly, I need to make a call to /api/auth/me which will return either a user object or null if the user is not logged in. To achiev ...

Exploring Angular 2's nested navigation using the latest router technology

Is there a way to implement nested navigation in Angular? I had this functionality with the previous router setup. { path: '/admin/...', component: AdminLayoutComponent } It seems that since rc1 of angular2, this feature is no longer supported. ...

Angular does not render components when the URL changes during navigation

I am attempting to create a simple routing functionality in an Angular application by navigating through components using button clicks. Although the URL path changes, the content within the component's view is not being rendered. I have set up the a ...

Troubleshooting the issue with generateStaticParams() in NextJs/TypeScript

My NextJs app has a products page that should render dynamic routes statically using generateStaticParams(). However, this functionality does not work as expected. When I run "npm run build," it only generates 3 static pages instead of the expected number. ...

typescript mock extending interface

I'm currently working with a typescript interface called cRequest, which is being used as a type in a class method. This interface extends the express Request type. I need to figure out how to properly mock this for testing in either jest or typemoq. ...

I'm having trouble getting my nav-tab to function properly in Bootstrap 4 when used with Angular 4. Can

I have been attempting to utilize Bootstrap 4 tabs with Angular 4 with the expectation that it would resemble and function similar to this example enter link description here However, my page is displaying like this. https://i.sstatic.net/dymNH.png Here ...

Transferring pictures between folders

I am currently developing an Angular app that involves working with two images: X.png and Y.png. My goal is to copy these images from the assets folder to a specific location on the C drive (c:\users\images) whose path is received as a variable. ...

What is the step-by-step process for implementing tooltips in Ant Design Menu after version 4.20.0?

According to the Ant Design documentation: Starting from version 4.20.0, a simpler usage <Menu items={[...]} /> is provided with enhanced performance and the ability to write cleaner code in your applications. The old usage will be deprecated in th ...

It appears that the blob data is not being received in the message sent from the websocket server to my Angular 2 Observable

Having trouble converting some html/javascript to Angular 2 and encountering an issue with blob data not being received in messages from the websocket host to the Angular 2 Observable. Text messages are being sent successfully from the websocket host, but ...

Ways to execute a jQuery function in Angular 2 post the completion of each component load

I've experimented with all the lifecycle hooks available, but I still haven't been able to achieve the desired outcome. What I'm trying to accomplish is to trigger a function that initializes multiple jQuery plugins for various elements on a ...

Could you lend a hand in figuring out the root cause of why this Express server is constantly serving up error

I am encountering a 404 error while running this test. I can't seem to identify the issue on my own and could really use another set of eyes to help me out. The test involves mocking a request to the Microsoft Graph API in order to remove a member fro ...