Error in MatSort implementation - Argument cannot be assigned

I'm having trouble figuring out how to implement the Mat-Sort functionality from Angular Material. When I try to declare my variable dataSource, I get the following error:

Argument of type 'Observable' is not assignable to parameter of type 'any[]'. Property length is missing in type 'Observable'.

Any suggestions on what I can do to fix this? Below you'll find the code for my component.ts and the related service.ts

component.ts

import { Component, OnInit, ViewEncapsulation, ViewChild } from '@angular/core';
import { Location } from '@angular/common';
import { DataSource } from '@angular/cdk/collections';
import { Observable } from 'rxjs/Observable';

import { MatTableDataSource, MatSort } from '@angular/material';

import { Report } from './../../models/report';
import { RepGenService } from './../../services/rep-gen.service';

@Component({
    selector: 'app-rep-gen-report',
    templateUrl: './rep-gen-report.component.html',
    styleUrls: ['./rep-gen-report.component.css'],
    encapsulation: ViewEncapsulation.None
})
export class RepGenReportComponent implements OnInit {
    reports: Report[];

    dataSource = new MyDataSource(this.repGenService);
    
    displayedColumns = ['report_id', 'caption'];

    constructor(private repGenService: RepGenService, private location: Location) { }

    ngOnInit() {
        this.getRepGen_Report();
    }

    getRepGen_Report(): void {
        this.repGenService.getReport()
            .subscribe(reports => this.reports = reports);
    }

    save(reports: Report[]) {
        this.repGenService.setReport(this.reports);
    }

    goBack(): void {
        this.location.back();
    }
}

export class MyDataSource extends DataSource<any> {
    constructor(private repGenService: RepGenService) {
        super();
    }
    connect(): Observable<Report[]> {
        return this.repGenService.getReport();
    }
    disconnect() { }
}

service.ts

import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders, HttpParams } from '@angular/common/http';

import { Observable } from 'rxjs/Rx';
import 'rxjs/add/operator/map';

const httpOptions = {
    headers: new HttpHeaders({ 'Content-Type': 'application/json' })
};

@Injectable()
export class RepGenService {

    constructor(public http: HttpClient) { }

    getReport(): Observable<any> {
        return this.http.get('/api/repGen_Report')
            .map(response => response);
    }

    setReport(reports) {
        this.http.post('/api/repGen_Report/update', reports
        ).subscribe();
    }
}

Thank you!

EDIT: Updated the component.ts file

Answer №1

The issue arises from the fact that your response is not loaded before the call to getRepGen_Report().

To resolve this, you need to subscribe to get the response in a callback. Since http.get is an asynchronous method, you have to handle it using promises or a workaround like setting the data source inside curly brackets:

view: any[] = [];
this.repGenService.get().subscribe(res => {
  this.view = res;
  this.dataSource = new TableDataSource(this.view);
})

After this step, you should declare a class called TableDataSource that extends DataSource and implement methods such as connect() and disconnect() within its constructor.

EDIT:

dataSource: MatTableDataSource;

ngOnInit() {
    this.repGenService.get().subscribe(res => {
      this.view = res;
      this.dataSource = new MatTableDataSource(this.view);
    });
  }

export class MatTableDataSource extends DataSource<any>{
constructor(private view:any[]){
    super();
  }
  connect(): Observable<any[]>{
      return this.view;
  }
  disconnect(){}
}

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

What is the process for updating nodemailer to integrate with https (SSL) connections?

I'm in the process of setting up an Angular website, and I've encountered a roadblock with the contact form. Initially, the form was functional on the insecure version of the site. However, after implementing a URL rewrite rule to force users to ...

Can you explain the significance of the colon in this context?

Upon reviewing some SearchKit code snippets (composed with react/jsx and es2015), I came across the following line in a jsx file: const source:any = _.extend({}, result._source, result.highlight) I am curious about the purpose or significance of the colo ...

Storing redux dispatch action using the useRef hook in Typescript

Currently, I am attempting to store the redux action dispatch in a React reference using useRef. My goal is to be able to utilize it for aborting actions when a specific button is clicked. Unfortunately, I am facing challenges with assigning the correct ty ...

Unable to access API hosted on localhost from Angular Client integrated with C# Backend running on a standalone server unit

I have an Angular Client (v14) and a .Net 6 WebAPI running on separate projects within a Raspberry Pi. The setup is for a standalone kiosk where both the front end and backend are hosted on the same device. My goal is to access the front end from a PC on ...

Tips for tuning a MatTable in angular without using a filterPredicate

I'm facing a challenge with my MatTable component where I need to filter the data using previously stored values from user input. While I can verify that the values match the data, I'm unsure of how to apply filtering without relying on the filte ...

The never-ending cycle of an Angular dropdown linked to a function being repeatedly invoked

I am currently working with a PrimeNg dropdown that is fetching its options through a function call. However, I have noticed that this function is being called an excessive number of times. Could this potentially impact the performance or any other aspect? ...

Searching for an Angular component in Selenium

After reviewing the HTML code snippet below, <div class="dx-filterbuilder-action-icon dx-icon-plus dx-filterbuilder-action" tabindex="0"> ::before </div> I attempted to locate this element using Selenium C# with the followin ...

Define an object in TypeScript without including a specific field type in the definition

Let's consider a scenario where there is an interface called Book: interface Book { id: number info: { name: string, } } Next, a list named bookList is defined: const bookList: Book[] = [ { id: 1, info: { ...

Choose a row by selecting the checkbox in the Kendo UI grid using TypeScript

I'm just starting out with Kendo UI and Angular 2, and I'm currently working on integrating Kendo UI with Angular 2. Specifically, I have a Grid Module set up with checkboxes in each row. My goal is to extract the row ID or any other field value ...

Retrieving the selected date from mat-datepicker into a FormControl

When creating a POST request to an API, I encountered an issue with the mat-datepicker field as it throws an error when inside the ngOnInit() call (since nothing is selected yet). Other fields like name, email, etc. work fine, but extracting a value from t ...

Why is TypeScript giving an error about an undefined object key, even though the key was assigned a value in the previous command?

type MaybeThereIsAValue = { [p: string]: string | undefined } ... let bar: MaybeThereIsAValue = {}; const key = "carpe"; bar[key] = "diem"; const why = bar[key]; // why is string | undefined I am confused as to why why is showing ...

In Certain Circumstances, Redirects Are Applicable

I have set up Private Routing in my project. With this configuration, if there is a token stored in the localStorage, users can access private routes. If not, they will be redirected to the /404 page: const token = localStorage.getItem('token'); ...

The challenge with the Optional Chaining operator in Typescript 3.7@beta

When attempting to utilize the Typescript optional chaining operator, I encountered the following exception: index.ts:6:1 - error TS2779: The left-hand side of an assignment expression may not be an optional property access. Here is my sample code: const ...

Tips for creating a universal event listener for keyPress events in Angular 5

This question pertains to the Angular 5 framework. Despite extensive research on topics like ElementRef and EventEmitter, I have been unable to find a straightforward method to programmatically trigger a global "Document scope" keyPress or keyDown event s ...

Programmatically click a button from the library by triggering a click on its outer div using Angular

Currently, I'm just starting out with Angular. I've been using the @abacritt/angularx-social-login package and noticed that the Google button it provides is only an icon. I'd like to customize its appearance by placing the icon inside a div ...

Is it possible to navigate to a particular step during an Angular IntroJS event?

Whenever I attempt to navigate to a specific step from within the IntroJS onexit event, it seems to cause confusion and display the incorrect step along with the highlighted element. I have defined my steps using JSON, with a total of 8 steps: [{ elem ...

Challenges with Typescript Integration in Visual Studio 2013

Currently diving into typescript as a newbie while going through the Angular tutorial using Visual Studio 2013 for work, which is also new to me. The frustrating part is that Visual Studio seems to be assuming I am going to use a different language (judgin ...

Can Angular PWA service worker be updated even when the browser is closed?

In my Angular PWA application, I have implemented a feature that checks for service worker updates every 15 seconds to ensure the cached static files are still valid. If there is a new deployment, the service worker silently updates the cache and notifies ...

Utilizing next/image as a backgroundImage in a div container

Currently, I am working with nextjs and I am trying to set a background Image for a specific div using next/image. Most of the sources I found only explain how to implement full screen background images with next/image, not for a single div. I stumbled upo ...

Typescript Next.js Project with Custom Link Button Type Definition

I have a project that includes a custom Button component and a NextLink wrapper. I want to merge these two components for organization purposes, but when I combine the props for each, I encounter an issue with spreading the rest in the prop destructuring s ...