【发布时间】:2018-09-24 12:15:24
【问题描述】:
我正在查看我现有项目之一中的 Angular 代码,并在 sn-p 下方找到。
我们正在使用Angular material datatable 在页面上渲染视图
export class Component implements OnInit,AfterViewInit{
private dataSource: MatTableDataSource<Product> = null;
@ViewChild(MatPaginator) paginator: MatPaginator;
columnsToDisplay = ['productId','productname'];
constructor(private _service : DataService) { }
ngOnInit() {
this._service.getProducts().subscribe(
((data : Product[]) => this.dataSource = new MatTableDataSource(data)),
() => console.log('THIS IS ERROR')
);
setTimeout(() => this.dataSource.paginator = this.paginator);
//this.dataSource.paginator = this.paginator;
}
ngAfterViewInit() {
this.dataSource.paginator = this.paginator;
}
}
我的问题是:
1) 由于this.service.getData() 返回一个Observable 并且subscribe 将在HttpResponse 可用时异步调用,
setTimeout 函数内部的操作是否会在仅在subscribe 方法被调用之后被调用?
2) 我看到ngAfterViewInit 方法也包含与setTimeout 方法完全相同的代码,ngOnInit 方法
3) 但是当这个方法被调用 (ngAfterViewInit) 时,this.products 仍然是 NULL 表示 subscribe 还没有被调用'
4) 这就是在ngOnInit 方法中调用setTimeout 的原因吗?
5)如果是这种情况,ngAfterViewInit方法有什么用?
【问题讨论】:
-
据我所知,没有理由拥有
setTimeouts 中的任何一个。似乎已经为产品设置了默认值,但这不需要异步完成。 -
我在我的问题中添加了更多细节。请检查
标签: javascript angular angular-material settimeout