【发布时间】:2020-03-18 18:39:47
【问题描述】:
我很困惑为 Angular Material Mat-Sort 功能编写代码。在声明我的变量 dataSource 时出现以下错误:
“Observable”类型的参数不能分配给“any[]”类型的参数。 'Observable' 类型中缺少属性长度。
你有什么我可以尝试的想法吗?下面你可以找到我的 component.ts 和相关 service.ts 的代码
组件.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);
//dataSource = new MatTableDataSource(this.repGenService.getReport()); // <--- error, not working
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();
}
//@ViewChild(MatSort) sort: MatSort;
//ngAfterViewInit() {
// this.dataSource.sort = this.sort; // therefor I need the imported MatTableDataSource
//}
}
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();
}
}
谢谢!
编辑:我更新了component.ts
【问题讨论】:
标签: angular typescript angular-material