Angular5:angular 何时完成页面加载?

Angular5: When angular finished page loading?

在我的 angular5 应用程序中,我使用了 table。 table 中的数据来自后端。当 table 第一次完全加载时,我想更改 table 内的滚动位置。为此,我正在这样做:

ngAfterViewInit() {
    setTimeout(function () {
        const scroller = document.getElementById('list-container');
        scroller.scrollTop = amountTop; // amountTop is the calculated height, which represents the centre of the table 
    }, 500);
}

有没有比使用 setTimeout() 函数更好的 DOM 操作方法?

如果您希望在加载数据时显示您的页面,我强烈建议使用 route resolves。这篇文章展示了如何构建和实现它,但我会尽量简短地解释它。

访问组件时不会加载数据,而是在访问某个 URL 时触发路由解析。这将从您的服务中获取数据并将其添加到路由快照数据中。从您的组件中,您可以通过 ActivatedRoute 访问此数据,并且只有在路由解析成功时才会加载您的组件。

文章没有解释的一件事是如何处理异常,但这里有一个代码片段,因此您不必显示空白页面。不过,我建议您在阅读文章后查看此内容。

resolve(route: ActivatedRouteSnapshot): Observable<MyObject> {
    return this.myService.getMyObjectById(route.params['id'])
        .map(myObject => {
            return myObject;
        })
        .catch(e => {
            console.error(e);
            return Observable.of([]); // You could return an other object.
            this.router.navigate(['404']); // Or you could redirect to a different page using the @angular/router
        });
}

更新

在你的具体情况下这意味着你可以调用

ngOnInit() {
    this.myList = this.route.snapshot.data['myList']
    const scroller = document.getElementById('list-container');
    scroller.scrollTop = amountTop;
}

现在您可以确定在调用 ngOnInit 方法时您的数据存在,因为组件仅在解析成功时加载

更新 2

如果你想在没有路由解析的情况下以异步方式加载数据,你可以这样解决

ngOnInit() {
    this.myService.getMyObjectByAParameter(myParameter).subscribe(
      myList => {
          this.myList = myList;
          const scroller = document.getElementById('list-container');
          scroller.scrollTop = amountTop;
      }, err => {
          // Handle your exception
      }
  );
}

如果你这样做,你的组件将始终被加载,但滚动将仅在 数据成功加载后设置。

您需要在 setTimeout 中的 API 调用成功时执行滚动顶部代码,超时为 0,以便 代码在打勾后执行,即在 angular 完成数据绑定后

this.marketService.getBuyOrder(marketId, start, limit)
.subscribe(data => { 
    const buyOrders = data; 
    if (buyOrders.length > 0) { 
        this.bids = this.bids.concat(buyOrders); 
    } else { 
        this.loadMore = false; 
    } 
    this.cd.markForCheck();

    // The timeout is set to 0 to allow angular to bind the array to view
    setTimeout(function () {
        const scroller = document.getElementById('list-container');
        scroller.scrollTop = amountTop;
    }, 0);
}, (err: HttpErrorResponse) => { Helper.handleError(err, this.alertService); });