我遇到了这样的错误:
[ts]类型'Company'的参数不能分配给类型的参数 '公司[]'。类型“公司”中缺少属性“包含”。
当我想将数组对象插入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;
}
已编辑。 CompanyService已添加:
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());
}
答案 0 :(得分:3)
TypeScript 上个月变得更加严格,所以现在的解决方案是:
dataSource: MatTableDataSource<any[]> = new MatTableDataSource<any[]>([]);
或者您可以禁用--strictPropertyInitialization
答案 1 :(得分:2)
我以前也有类似的问题。
我通过设置解决了问题
dataSource: MatTableDataSource<any[]>;
然后
this.dataSource = new MatTableDataSource(companies);
答案 2 :(得分:0)
只需这样声明您的数据源:
dataSource = new MatTableDataSource(this.trainingService.getData());
@ViewChild(MatSort) sort: MatSort;
constructor(private trainingService: TrainingService) {}
然后从@ angular / core导入工具ngAfterViewInit女巫
ngAfterViewInit(){
this.dataSource.sort = this.sort;
}
希望这会有所帮助
答案 3 :(得分:0)
我通过在导入末尾添加/ table来解决此错误:
import { MatTableDataSource } from '@angular/material/table';