我有一个奇怪的例子,我无法通过它,也不知道它是如何发生的,所以我在这里得到了名为SiteComponent的父组件--类型记录逻辑:
ngOnInit(): void {
this.subs.push(
this.route.data.subscribe(data => {
this.siteTemplate$ = this.dataService.getMappedData(`data${data.type}`).pipe(
map(_data => ({..._data, dataType: data.type })),
)
})
);
}在这里,模板文件代码:
<div class="app-site">
<ng-container *ngIf="!siteTemplate$ | async">
<div fxLayout="row"
fxLayoutAlign="center"
style="margin-top: 60px;">
<mat-spinner></mat-spinner>
</div>
</ng-container>
<ng-container *ngIf="siteTemplate$ | async">
<app-filters (filtersChanged)="applyFilters()"></app-filters>
<div class="app-site-section">
<div class="app-site-section-column" id="charts">
<app-linear-chart *ngFor="let record of (siteTemplate$ | async)?.chartsData.records"
[categories]="(siteTemplate$ | async)?.chartsData.categories"
[chartData]="record"
></app-linear-chart>
</div>
<div class="app-site-section-column">
<app-pie-chart *ngFor="let record of (siteTemplate$ | async)?.chartsData.records"
[categories]="(siteTemplate$ | async)?.chartsData.categories"
[chartData]="record"
></app-pie-chart>
</div>
</div>
<div>{{siteTemplate$ | async | json}}</div>
<div fxLayout="row"
fxLayoutAlign="center"
id="table"
class="app-site-section"
>
<app-table [tableData]="(siteTemplate$ | async)?.tableData"
[dataType]="(siteTemplate$ | async)?.dataType"
></app-table>
</div>
</ng-container>
</div>正如您所看到的,它由几个依赖于异步管道的子组件组成,图表工作得很好,但是表也有问题。
table.ts
export class TableComponent implements AfterViewInit, OnInit {
@Input() tableData: any = {records: []};
@Input() dataType: any;
dataSource: MatTableDataSource<any> ;
@ViewChild(MatPaginator) paginator: MatPaginator;
@ViewChild(MatSort) sort: MatSort;
constructor() {
}
ngOnInit(): void {
console.log(this.tableData);
this.dataSource = new MatTableDataSource(this.tableData.records);
}
ngAfterViewInit(): void {
this.dataSource.paginator = this.paginator;
this.dataSource.sort = this.sort;
}
}这里我得到了一个错误,因为console.log(this.tableData)返回null,但是tableData在siteTemplate$中从不为null,因为我通过添加tap和记录这个值来检查它,这个值总是以对象的形式出现。
发布于 2021-03-27 11:49:44
您有多个siteTemplate$ | async,每个都会订阅可观察到的内容,所以siteTemplate$ | async可以是null。要防止这种情况,只使用siteTemplate$ | async一次:
<ng-container *ngIf="siteTemplate$ | async as siteTemplate; else other">
...
<app-table [tableData]="siteTemplate.tableData"
[dataType]="siteTemplate.dataType"
></app-table>
</ng-container>
<ng-template #other>
<div fxLayout="row"
fxLayoutAlign="center"
style="margin-top: 60px;">
<mat-spinner></mat-spinner>
</div>
</ng-template>发布于 2021-03-27 11:49:58
通过使用异步管道,您不能期望在创建自异步的子组件时立即获得异步结果。因此,应该侦听ngOnChanges生命周期的结果。
ngOnChanges(): void {
console.log(this.tableData);
this.dataSource = new MatTableDataSource(this.tableData.records);
}https://stackoverflow.com/questions/66830473
复制相似问题