【发布时间】:2018-12-02 08:36:15
【问题描述】:
我遇到了这样的错误:
[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());
}
【问题讨论】:
-
您似乎遇到了类型错误。试试这个
companies : Array<Company>; -
看起来 companyService.getCompanies() 返回一个公司数组,但 MatTableDataSource
需要一个公司。您可能希望将其设置为 MatTableDataSource . -
在我尝试之后,this.companies 上也出现了同样的错误。我做了 MatTableDataSource
,但仍然没有变化。 -
当我尝试 console.log(companies) 时,它会返回一个包含两个对象的数组,如下所示:[{…}, {…}]
-
我现在在您的代码中找不到任何错误。页面加载时是否出现错误?是调用服务的时候吗?你知道它可能是什么线吗?该错误看起来您的服务可能存在输入错误,这里是 example 其他人如何解决它