Issue TS2345: Cannot assign type 'UserDataSource' to type '{}'[] in the parameter

I'm having trouble sorting the table using MatTableDataSource...

I'm struggling to figure out how to pass an array to MatTableDataSource. I want the data in the table to be displayed and sorted accordingly.

//Component.ts file

export class TestSortTableComponent implements OnInit {

displayedColumns = ['fullName', 'birthDate', 'phone', 'email', 'skype', 
'position', 'startDate', 'endDate', 'action'];

data: UserDataSource ;

dataSource = new MatTableDataSource(this.data);
@ViewChild(MatSort) sort: MatSort;
constructor(
private userService: UserService,
private activatedRoute: ActivatedRoute,
private tableQueryParams: TableQueryParamsService,
private httpService: UserService,
private router: Router
)  {}

ngOnInit() {  
this.data = new UserDataSource(this.userService, this.activatedRoute);
}
}

//HTML code:

<table mat-table [dataSource]="dataSource" matSort class="mat-elevation- 
z8">

<ng-container matColumnDef="fullName">
<mat-header-cell *matHeaderCellDef >Full name</mat-header-cell>
<mat-cell *matCellDef="let user">{{ user.fullName }}</mat-cell>
</ng-container>

<ng-container matColumnDef="birthDate">
<mat-header-cell *matHeaderCellDef mat-sort-header>Birthday</mat-header- 
cell>
<mat-cell *matCellDef="let user">{{ user.birthDate | date }}</mat-cell>
</ng-container>

<mat-header-row *matHeaderRowDef="displayedColumns"></mat-header-row>
<mat-header-row *matRowDef="let row; columns: displayedColumns"></mat- 
header-row>
</table>



//UserDataSource.ts file:


export class UserDataSource implements DataSource<UserModel> {
[x: string]: any;
public usersSubject = new BehaviorSubject<PagedContentModel>({
    items: [],
    total: 0
});
private queryParamsSubscriber: Subscription;
paginator: any;
sort: any;


constructor(
    private userService: UserService,
    private activatedRoute: ActivatedRoute,

) { }

public connect(collectionViewer: CollectionViewer): 
Observable<UserModel[]> {
    this.queryParamsSubscriber = 
this.activatedRoute.queryParamMap.subscribe((paramMap) => {
        this.loadUsers(
            +paramMap.get('page'),
            paramMap.get('sortBy'),
            paramMap.get('sortOrder'),
            paramMap.get('gender'),
            paramMap.get('startDate'),
            paramMap.get('endDate'),
            paramMap.get('keyWord'),

        );
    });
    return this.usersSubject.asObservable()
        .pipe(
            map((response) => response.items)
        );
 }

 disconnect(collectionViewer: CollectionViewer) {
    this.queryParamsSubscriber.unsubscribe();
    this.usersSubject.complete();
 }

 getTotalObservable(): Observable<number> {
    return this.usersSubject.asObservable()
        .pipe(
            map((response) => response.total)
        );
 }

 private loadUsers(page = 0, sortBy = '', sortOrder = 'asc', gender, 
 startDate, endDate,keyWord) {
    const f = {
        gender,
        startDate,
        endDate,
        keyWord
    };
    this.userService.getUsers(page, sortBy, sortOrder, 
f).subscribe((response) => {
        this.usersSubject.next(response);
    });
}
}


//getUser method:

getUsers(page = 0, sortBy = '', sortOrder = 'asc', filter): 
Observable<any> {
let params: HttpParams = new HttpParams()
  .set('page', page ? page.toString() : '0')
  .set('sortBy', sortBy || '')
  .set('sortOrder', sortOrder || '');

if (filter) {
  for (let key in filter) {
    let value = filter[key];
    if(value){

      params = params.set(key, value);
    }
  }
 }

 return this.http.get(`${environment.apiBaseUrl}/employees`, { params });

 }

The issue I'm facing is with transferring the desired list into MatTableDataSource which is causing the sorting not to work as expected.

Although everything seems straightforward in the official Angular Material documentation, I have encountered unknown problems that are likely related to UserDataSource implementation.

Answer №1

Creating the dataSource should come after setting up the data:

this.data = new UserDataSource(this.userService, this.activatedRoute);

This might not completely solve your issue, but it's a good starting point :)

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

The synergy between ternary operators and Vue filters

Recently, I came across a peculiar issue while working with Vue. Take a look at the code snippet from vue.html: <label :text= "$props.information ? (($props.information.primary || $props.information.secondary) | myFilter) : `No info`"> </lab ...

Converting TypeScript to JavaScript in a React JS application: Steps and best practices

As a beginner in the world of React, I am currently struggling with transitioning from TypeScript to JavaScript The code snippet below demonstrates the use of table filter with TypeScript. How can I adapt this code to utilize JavaScript instead? Click he ...

Trouble retrieving information from my axios fetch response

Can anyone help me identify the issue in my code? I am working on a simple API get request. It successfully retrieves data from my API: const GetMedicalPackages = async (props:IGetMedPack)=>{ const token = props.token const data = axios({ ...

How can I alter the appearance of HTML text when hovering over the enclosing div?

I want the text to change color and zoom when the cursor is near it (when the mouse enters the area of the div containing the text). Currently, I am able to change the text color only when hovering directly over it. Below is a snippet of the code. HTML: & ...

Can sweetalert2 be used as a tooltip?

I have a query, is it feasible to include a tooltip in the alert message? Alternatively, could there be another tooltip option available? Swal.fire({ title: '<strong>An example with HTML tags</strong>', icon: 'info', ...

Is there a way to turn off the warning overlay in a React application?

I’m currently using react-app-rewired and I am trying to figure out how to turn off the overlay that displays Typescript warnings whenever I compile. It seems like some warnings that are not caught by the VSCode Typescript checker pop up on this overlay ...

Issue with callback function causing incorrect type inference

Here is a simplified code snippet: interface Store<T> { value: T } type AnyStore = Store<any> type StoreValue<T> = T extends Store<infer V> ? V : never function computed< V, D extends AnyStore, S extends Store<V> ...

failure of pipe during search for art gallery information

Hi, I've created a filter pipe to search for imagenames and imageids among all my images. However, it seems to only find matches in the first image. There seems to be something wrong with my code. This is my FilterPipe class in filter.pipe.ts where I ...

Tips on preventing the copying of .txt and .xml files with the fs-extra.copySync function

Currently, I am working on a small TypeScript assignment and facing an issue that I can't seem to solve. Any guidance or advice on the problem mentioned below would be greatly appreciated. The task at hand involves copying a directory from one locati ...

Using React and TypeScript to Consume Context with Higher Order Components (HOC)

Trying to incorporate the example Consuming Context with a HOC from React's documentation (React 16.3) into TypeScript (2.8) has been quite challenging for me. Here is the snippet of code provided in the React manual: const ThemeContext = React.creat ...

Having trouble with executing a "POST" operation in Spring framework?

After sending data from the angular service class, I included three parameters letter, documents, empList for the POST operation to the Api. export class LetterService { private baseUrl = 'http://localhost:8080/api/letter'; constructor(priv ...

Having an issue with my code in angular 12 where I am unable to successfully call an API to retrieve a token, and then pass that token to another API for further processing

Here is the code snippet containing two methods: getToken and validateuser. I am fetching the token from getToken and passing it as a parameter to validateuser. However, before retrieving the token, my second API call is being executed. ...

Issue encountered with redux-toolkit's createAsyncThunk functionality

Here is how I implemented the deleteDirectories method in redux: export const deleteDirectories = createAsyncThunk( "directories/deleteDirectories", async (id, thunkAPI) => { try { const response = await axios.delete(`${url}direc ...

What prevents ts-morph from retrieving the classes within a TypeScript project?

Utilizing ts-morph, I am examining the inheritance relationships of classes in a project: For testing purposes, I have downloaded an open-source projectantv/x6: import { Project } from "ts-morph"; const project = new Project(); project.addDire ...

Tips for detecting changes in @Input values

There is a component that has the following input: @Input() list: Array<string> I want to know how I can detect when the parent component changes the value of this input. ...

Using TypeScript to extract types from properties with specific types

My current challenge involves working with a filter object derived from an OpenAPI spec. The structure of this object is illustrated below: export interface Filters { field1: string[] field2: string[] field3: boolean field4: number } My goal is to ...

I'm having trouble with my code not working for get, set, and post requests. What could be causing this issue and how can I

Here are the TypeScript codes I've written to retrieve product details and delete them. import { Component, OnInit } from '@angular/core'; import {FormGroup,FormBuilder, FormControl, Validators} from "@angular/forms" // other impor ...

The setInterval function is active in various components within Angular 6

Recently, I started using Angular(6) and incorporated the setInterval function within a component. It's functioning properly; however, even after navigating to another route, the setInterval continues to run. Can someone help me determine why this is ...

Updating the button text in Angular 7

Here's a question: <button (click)="activateMotion(1)"> <img class="emotion-icon" id="positive-icon" src="" /> </button> <button (click)="activateMotion(-1)"> <img class="emotion-icon" id="negative-icon" src="" /&g ...

When I select a checkbox in Angular 2, the checkall function does not continue to mark the selected checkbox

How can I check if a checkbox is already marked when the selectAll method is applied, and then continue marking it instead of toggling it? selectAll() { for (let i = 0; i < this.suppliersCheckbox.length; i++) { if (this.suppliersCheckbox[i].type == " ...