Angular SwitchMap is a powerful operator that allows you

I am currently utilizing the mat-table component from angular material, in conjunction with pagination features.

Whenever a user inputs text into the search field, a filter method is activated to send the text, page size, and current page to the backend for search purposes.

To optimize performance, I attempted to implement the switchmap function to cancel previous requests. This way, only the latest request will be processed, preventing multiple calls to the server for each keystroke.

In addition, debounceTime is also being utilized to set a delay after the user stops typing before initiating the call.

Displayed below is the filter method triggered by user input in the search field:

_search$: Subject<string> = new Subject<string>();
search = '';


 applyFilter(search: string) {
    this._search$.next(search.toLocaleLowerCase());
    this._search$.pipe(
      debounceTime(GlobalVariables.DEBOUNCETIME),
    )
      .subscribe((data: string) => {
        this.currentPage = 0;
        this.loadData(data, this.pageSize, this.currentPage);
      });
  }

Another method responsible for querying the database and updating the table:

 loadData(search: string = '', limit: number, page: number) {
    if (search === 'sim') {
      search= 'true';
    } else if (search === 'nao' || search === 'não') {
      search= 'false';
    }
    this.service.listartecnicosPaginacao(search, limit, page).subscribe((res: any) => {
      this.dataSource.data = res['lista'];
      setTimeout(() => {
        this.paginator.pageIndex = this.currentPage;
        this.paginator.length = res.totalElemento;
      });
    });
  }

My attempt to integrate switchMap into the code resulted in the following message:

 applyFilter(search: string) {
    this._search$.next(search.toLocaleLowerCase());
    this.currentPage = 0;

    this._search$.pipe(
      debounceTime(VariaveisGlobais.DEBOUNCETIME),
      switchMap(data => this.loadData(data, this.pageSize, this.currentPage))
    )
      .subscribe();
  }

Despite adjusting the syntax as suggested, the error message persisted:

(method) ListTableComponent.loadData(search: string | undefined, limit: number, page: number): voidType 'void' is not assignable to type 'ObservableInput<any>'.ts(2322) switchMap.d.ts(2, 79): The expected type comes from the return type of this signature.list-table.component.ts(94, 17): Did you mean to mark this function as 'async'?

The issue remained even after modifying the switchMap parameter.

Answer №1

The function loadData does not have a return value, which is why it is marked as 'void'

return this.service.listTechniciansPagination...

When applying the filter, only the subject should be triggered:

applySearchFilter(search: string) {
    this._search$.next(search.toLowerCase());
}

Make sure to subscribe to the _search$ observable in ngOnInit or similar lifecycle hook

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

Node.js interacting with a MySQL database to create a RESTful API

I am attempting to utilize query parameters with MySQL and NodeJS, but I am not receiving any response in the console. Instead, I am getting all students' details as output. app.get('/api/students', (req, res) => { const name = req.query ...

Saving information obtained through Angular subscribe into a variable

One of the services I have is called getWeather, which contains a method that communicates with an API using longitude and latitude parameters and then returns the response: import { Injectable } from '@angular/core'; import { HttpClient } from ...

"What are the necessary components to include in UserDTO and what is the reasoning behind their

Presenting the User entity: package com.yogesh.juvenilebackend.Model; import jakarta.annotation.Generated; import jakarta.persistence.*; import lombok.*; @Entity @Getter @Setter @NoArgsConstructor @AllArgsConstructor @RequiredArgsConstructor public class ...

What is the best way to implement a <Toast> using blueprintjs?

Struggling without typescript, I find it quite challenging to utilize the Toast feature. This component appears to have a unique appearance compared to the others. Shown below is an example code. How would you convert this to ES6 equivalent? import { But ...

I need to create a login form using Angular - what steps should I follow?

I'm currently in the process of developing a login form for my website. Utilizing angular, express, and mongoDB. Below is the login function controller I have implemented: loginUser: (req, res) => { User.findOne({ username: req.bo ...

Combining Rollup, Typescript, and converting images to base64 during the loading process

Having trouble preloading an image with Rollup. None of the solutions that should work seem to be effective, and I can't figure out why. Has anyone successfully managed to make this work? Here is my configuration in rollup.config.js: import image fr ...

What role does the empty object type {} play in typescript?

In the @types/React package of the DefinitelyTyped library, I came across this definition: interface FunctionComponent<P = {}> { (props: PropsWithChildren<P>, context?: any): ReactElement | null; propTypes?: WeakValidationMap&l ...

Using Jest and Supertest for mocking in a Typescript environment

I've been working on a mock test case using Jest in TypeScript, attempting to mock API calls with supertest. However, I'm having trouble retrieving a mocked response when using Axios in the login function. Despite trying to mock the Axios call, I ...

Error message: Conflicting type declarations across multiple files

I am facing a challenge with my TypeScript 'snippets' project. It seems that multiple .ts files contain type names (like Foo) that are the same. //file-a.ts type Foo = { } //file-b.ts type Foo = { } When attempting to compile, I encounter ...

Today is a day for coming together, not for waiting long periods of

When grouping by month and dealing with different days, I encountered an issue similar to the one shown in this image. https://i.stack.imgur.com/HwwC5.png This is a snapshot of my demo code available on stackblitz app.component.html <div *ngFor="let ...

Issue with conflicting namespaces warning when compiling an Angular 9 project with ng-packagr using Typescript

I'm trying to pinpoint the root cause of this problem, and I suspect it may be related to Typescript. However, it could also involve ng-packagr or Angular. This issue only arose after upgrading to Angular 9. Upon building my production environment, I ...

A long error occurred while using the payloadaction feature of the Redux Toolkit

import { createSlice, PayloadAction, createAsyncThunk } from "@reduxjs/toolkit" import axios, { AxiosError} from "axios" type user = { id: number, token: string } export type error = { error: string } interface authState { user: user | ...

Setting up ESM for Firebase functions: A step-by-step guide

Our server application needs to utilize the most recent ipfs-http-client as it is an authorized package for accessing IPFS. However, the project must switch to using ESM starting from v57.0.0. I have invested a significant amount of time into this and it h ...

How to efficiently import an external ES module from a URL using TypeScript

I've recently started experimenting with Observable notebooks and I must say, it's been a great experience so far. Now, my next goal is to integrate a notebook into my web app. The following vanilla JavaScript code using JavaScript modules accomp ...

What is the best way to create a personalized filter function for dates in JavaScript?

I am working with a DataTable that includes a column called Timestamp: <p-dataTable sortMode="multiple" scrollable="scrollable" scrollHeight="150" [value]="currentChartData" #dt> <p-column field="timestamp" header="Timestamp" [sortable]=" ...

Best Practices for Variable Initialization in Stencil.js

Having just started working with Stencil, I find myself curious about the best practice for initializing variables. In my assessment, there seem to be three potential approaches: 1) @State() private page: Boolean = true; 2) constructor() { this.p ...

How to retrieve a string in an Angular 6 http get request

Having trouble retrieving a string from my request. fetchData(id: string): string { let result: string = ''; this.dataService.getData(id).subscribe( response => { result = response.body.value; }, error => { cons ...

Choose the object's property name using TypeScript through an interface

Consider a simplified code snippet like the following: interface MyBase { name: string; } interface MyInterface<T extends MyBase> { base: MyBase; age: number; property: "name" // should be: "string" but only p ...

What is the best method to remove a value from a JSON object in a CSV file?

I received a JSON response like this: xxx: ["fsd,das"] I am looking for a way to remove the value "fsd" from the JSON object. The issue is that the response inside the JSON is not actually an array, but rather a CSV format. How can I go about deleting it ...

Tips for configuring TypeScript in a monorepo to successfully compile private packages

I have configured a monorepo using turborepo that includes Nestjs for the backend and Nextjs for the frontend. To reuse prisma definitions, I separated them into their own package with its own tsconfig. In the index file of my database package where prism ...