我想在我的角度材料表中显示来自我的 api 的数据,但我有一个我不明白的错误。
错误:
出现在 AppModule 的 NgModule.imports 中,但本身有错误。
'name' 属性没有初始化器,也没有在构造函数中永久赋值。
显示所有属性的错误
ts.file
export class ProductTableComponent implements OnInit {
displayedColumns: string[] = ['position', 'name', 'weight', 'symbol'];
public dataSource: MatTableDataSource<Product>;
constructor(private productService: ProductService) {
this.dataSource = new MatTableDataSource<Product>()
}
ngOnInit(): void {
this.getAllProduct();
}
getAllProduct() {
let resp = this.productService.getAlL();
resp.subscribe(result => {
this.dataSource = new MatTableDataSource<Product>();
this.dataSource.data = result as Product[];
})
}
product.module
@NgModule({
declarations: [
ProductMessageComponent,
ProductPageComponent,
ProductTableComponent
],
imports: [
RouterModule.forChild(appRoutes),
MatTableModule,
HttpClientModule,
Product
],
exports: [
RouterModule
],
providers: [ProductService],
})
export class ProductModule { }
app.module
@NgModule({
declarations: [
AppComponent,
HeaderComponent,
FooterComponent
],
imports: [
BrowserModule,
AppRoutingModule,
HelloModule,
ProductModule,
BrowserAnimationsModule,
MatToolbarModule,
MatIconModule,
MatMenuModule,
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
product.ts
export class Product {
name: string;
position: number;
weight: number;
symbol: string;
}
答案 0 :(得分:0)
您的 app.module.ts
文件中缺少一些导入。对于 name
错误,有两种方法可以解决此问题:
如果您使用的是 VSCode,则需要更改所使用的 TS 版本 编辑器使用。
只需在构造函数中声明数组时对其进行初始化即可。
app.module.ts
@NgModule({
declarations: [
AppComponent,
HeaderComponent,
FooterComponent
],
imports: [
BrowserModule,
AppRoutingModule,
HelloModule,
ProductModule,
BrowserAnimationsModule,
MatToolbarModule,
MatIconModule,
MatMenuModule,
MatSortModule,
MatTableModule,
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
解决 name has no initializer
错误。
public dataSource: MatTableDataSource<Product>();
constructor(private productService: ProductService) { }
要使您的更改反映在表格中,
getAllProduct() {
let resp = this.productService.getAlL();
resp.subscribe(result => {
this.dataSource.data = result as Product[];
this.dataSource._updateChangeSubscription();
})
}