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

Is there a way to incorporate several select choices using specific HTML?

I am currently trying to dynamically populate a select tag with multiple option tags based on custom HTML content. While I understand how to insert dynamic content with ng-content, my challenge lies in separating the dynamic content and wrapping it in mat ...

Display content based on selected option

I am struggling to display a div based on the selection I make. Unfortunately, it's not working as expected. Can anyone offer guidance on how to tackle this issue? <div class ="row"> <div class="form-group col-md-6"> <label for= ...

What is the best way to merge two approaches for tallying items within each category?

I have an Angular 8 application that includes two methods for displaying the number of items in each category. These items are retrieved from the back-end and are categorized as follows: <mat-tab> <ng-template mat-tab-label> ...

Tips for inserting a line break within the output of an Angular pipe

Is there a way to display dates on separate lines in an Angular pipe? <th>{{(date | date: 'EEE MMM d')}}</th> Currently, the output is displayed like Mon Jul 20 - all in the same line. But I want it to be displayed like: Mon Jul ...

Is there a way to modify the style when a different rarity is selected in Next.JS?

Is there a way to change the style depending on the rarity selected? I am currently developing a game that assigns a random rarity upon website loading, and I am looking to customize the color of each rarity. Here is how it appears at the moment: https:/ ...

The flexibility of adjusting the percentage in the ng-circle-progress feature

Currently, I am utilizing ng-cycle-progress in my Angular progress. Here is the HTML code: <circle-progress [percent]="score" [radius]="100" [outerStrokeWidth]="16" [innerStrokeWidth]="8" [outerStrokeColor]="'#78C000'" [innerStrok ...

Notifying other components in Angular 2 through event broadcasting

Feeling a bit overwhelmed here. I'm diving into Angular 2 for the first time and trying to grasp how sibling child components can communicate with each other. I have n child components capable of playing an Audio file. The objective is to stop the p ...

Choose FormGroup using Angular Directive

Can Angular reactive form controls be selected for a custom directive in a different way? Take a look at this code snippet: @Directive({ selector: '[formControl], [formControlName]', }) export class MyDirective { constructor( priv ...

Failure to trigger the before-prepareJSApp hook in nativescript-dev-webpack

I am currently facing some challenges while trying to bundle my Nativescript app using webpack. The first issue arises when I run the following command: tns build android --bundle After running this command, it seems like webpack is not doing anything. ...

Error message "After the upgrade to Angular 15, the property 'selectedIndex' is not recognized in the type 'AppComponent'."

My Ionic 6 app with capacitor has been updated in the package.json file. These are the changes: "dependencies": { "@angular/common": "^15.1.0", "@angular/core": "^15.1.0", "@angular/forms": "^15.1.0", "@angular/platform-browser": "^15.1. ...

Failure parsing occurred when attempting to make an HTTP POST request from Angular to a PHP server

When I try to consume the PHP endpoint from Postman, everything works fine. But when I attempt to do the same from an Angular post request, I encounter an error - Http failure during parsing for. Even though I have double-checked my code and it all seems c ...

Is there a way to use WithStyles<typeof styles> within Material UI?

import { WithStyles, createStyles } from '@material-ui/core'; const styles = (theme: Theme) => createStyles({ root: { /* ... */ }, paper: { /* ... */ }, button: { /* ... */ }, }); interface Props extends WithStyles<typeof styles> ...

I am currently facing challenges retrieving data from a post request in my Angular/Typescript frontend application connected to an ASP.NET backend

I am currently working on a web application that relies on backend processing. To communicate between my Angular(v14)/Typescript front end and an ASP.NET backend, I am sending a post request. Backend Code [HttpPost] public async Task<string> Process ...

What is the process for accessing my PayPal Sandbox account?

I'm having trouble logging into my SandBox Account since they updated the menu. The old steps mentioned in this post Can't login to paypal sandbox no longer seem to work. Could someone please provide me with detailed, step-by-step instructions o ...

TypeScript is unable to detect the .sequelizerc configuration file

I have a file called .sequelizerc which contains the following configuration: const path = require('path'); module.exports = { config: path.resolve('.', 'src/config/sequelizeCLIConfig.json'), 'migrations-path': ...

Issue with Next.js: Callback function not being executed upon form submission

Within my Next.js module, I have a form that is coded in the following manner: <form onSubmit = {() => { async() => await requestCertificate(id) .then(async resp => await resp.json()) .then(data => console.log(data)) .catch(err => console ...

Utilizing Typescript and sinon to mock the functionalities of jsonwebtoken

Looking for help with mocking the function verify in Typescript's jsonwebtoken library. I've installed typescript, jsonwebtoken, sinon, mocha, and chai along with their corresponding types. However, when trying to stub the function, an error occu ...

Transform a javascript object with class attributes into a simple object while keeping the methods

I am seeking a way to convert an instance of a class into a plain object, while retaining both methods and inherited properties. Here is an example scenario: class Human { height: number; weight: number; constructor() { this.height = 1 ...

Merging two promises into a single promise in Angular

In my application, I am facing a challenge with implementing a method named loadAll. What I need to accomplish is to make calls to 2 different HTTP methods in order to load the necessary data. Both of these methods return promises. However, when I attem ...

How to convert form fields into JSON format using Angular 2

Currently, I am in the process of learning angular2 and have encountered a roadblock. I have created a form where the values are populated through JSON. The form consists of both pre-filled fields and text input fields where users can enter data and select ...