我收到这样的错误:
[ts]“公司”类型的参数不能分配给“公司[]”类型的参数。 “公司”类型中缺少财产“包含”。
当我想将一个数组对象插入MatTableDataSource时。这是我的TypeScript文件:
import { Component, OnInit, ViewChild } from '@angular/core';
import { MatTableModule } from '@angular/material/table';
import { MatTableDataSource, MatPaginator, MatSort } from '@angular/material';
import { CompanyService } from '../../../services/company.service';
import { AuthService } from '../../../services/auth.service';
import { DataSource } from '@angular/cdk/collections';
import { Company } from '../../../models/company.model';
import { Observable } from "rxjs";
import { Router } from '@angular/router';
import { filter } from 'rxjs/operators';
@Component({
selector: 'app-index-company',
templateUrl: './index-company.component.html',
styleUrls: ['./index-company.component.css']
})
export class IndexCompanyComponent implements OnInit {
company : Object;
companies : Object;
displayedColumns = ['perusahaan', 'kategori', 'mahasiswa', 'option'];
dataSource: MatTableDataSource<Company>;
@ViewChild(MatPaginator) paginator: MatPaginator;
@ViewChild(MatSort) sort: MatSort;
applyFilter(filterValue: string) {
filterValue = filterValue.trim();
filterValue = filterValue.toLowerCase();
this.dataSource.filter = filterValue;
}
constructor(
private companyService: CompanyService,
private authService: AuthService,
private router: Router
)
{
this.companyService.getCompanies().subscribe(companies => {
this.companies = companies;
this.dataSource = new MatTableDataSource(companies);
},
err => {
console.log(err);
return false;
});
}
ngOnInit() {
}
}
这是我的公司型号:
export class Company{
perusahaan : String;
alamat : String;
deskripsi : String;
telepon : String;
email_perusahaan : String;
website : String;
students = [];
kategori : String;
author : String;
update_by : String;
status : String;
}
编辑。公司服务已添加:
getCompanies(): Observable<Company>{
let headers = new Headers();
headers.append('Authorization', this.authToken);
headers.append('Content-Type', 'application/json');
return this.http.get(this.baseUri+'/companies', {headers: headers})
.map(res => res.json());
}
我之前有类似的问题。 我通过设置解决了这个问题
dataSource: MatTableDataSource<any[]>;
然后
this.dataSource = new MatTableDataSource(companies);
只需声明您的数据源如下:
dataSource = new MatTableDataSource(this.trainingService.getData());
@ViewChild(MatSort) sort: MatSort;
constructor(private trainingService: TrainingService) {}
然后实现ngAfterViewInit女巫从@ angular / core导入
ngAfterViewInit(){
this.dataSource.sort = this.sort;
}
希望这可以帮助