Angular4 ngAfterViewChecked在使用setTimeout时多次调用

Angular4 ngAfterViewChecked在使用setTimeout时多次调用,angular,Angular,我有一个服务,我想在视图完全呈现后调用它。我做了一些挖掘,发现了角的生命周期。似乎对我来说最好的方法是查看后检查AppComponent,因此我更新了我的AppComponent,并添加了: 从“@angular/core”导入{Component,OnInit,AfterViewChecked}; 从“@angular/router”导入{ActivatedRoute,Params}”; 从“/shared/results.service”导入{ResultsService}”; 从“/sha

我有一个服务,我想在视图完全呈现后调用它。我做了一些挖掘,发现了角的生命周期。似乎对我来说最好的方法是查看后检查
AppComponent
,因此我更新了我的AppComponent,并添加了:

从“@angular/core”导入{Component,OnInit,AfterViewChecked};
从“@angular/router”导入{ActivatedRoute,Params}”;
从“/shared/results.service”导入{ResultsService}”;
从“/shared/height.service”导入{HeightService};
@组成部分({
选择器:“bzRoot”,
templateUrl:“./app.component.html”,
样式URL:['./app.component.scss']
})
导出类AppComponent实现OnInit,AfterViewChecked{
建造师(
专用_activatedRoute:activatedRoute,
private\u resultsService:resultsService,
私人高度服务:高度服务
) { }
恩戈尼尼特(){
this._activatedRoute.queryParams.subscribe((params:params)=>this._resultsService.elq=params['elq']);
}
ngAfterViewChecked(){
console.log('hi');
}
}
当我运行应用程序时,我可以看到控制台中有25个“hi”实例。我不知道为什么这么多,但这不是问题所在。 我的方法是调用我创建的服务,该服务使用
postMessage
向父窗口发送消息。看起来是这样的:

从'@angular/core'导入{Injectable};
@可注射()
出口级高度服务{
构造函数(){}
公共大小调整(){
console.log(“调整大小”);
var body=document.body,
html=document.documentElement;
变量高度=数学最大值(
身高,
身体,在视线之外,
body.clientHeight,
html.offsetHeight
);
setTimeout(函数(){
postMessage(高度,“*”);
}, 0);
}
}
我的
ngAfterViewChecked
方法现在如下所示:

ngAfterViewChecked(){
此._heightService.resize();
}
如果我注释掉
setTimeout
行,它将返回到25次调用。 有人知道我为什么以及如何阻止它发生吗?

这是故意的。报告说:

ngAfterViewChecked()
角度检查零部件视图和子视图后响应。 在ngAfterViewInit和每个后续ngAfterContentChecked()之后调用。 只有组件的挂钩

您正在寻找ngAfterViewInit()钩子

编辑:似乎角度挂钩不是您需要的解决方案,您应该保存最后发送的高度值,并仅在值更改时触发调整大小

import { Injectable } from '@angular/core';

@Injectable()
export class HeightService {

  lastHeightPosted = null;
  constructor() { }

  public resize() {
    console.log('resizing');

    var body = document.body,
        html = document.documentElement;

    var height = Math.max( 
      body.scrollHeight, 
      body.offsetHeight, 
      body.clientHeight, 
      html.offsetHeight
    );

    if ( lastHeightPosted !== height) {
        parent.postMessage(height, '*');
        lastHeightPosted = height;
    }
  }

  ngAfterViewChecked() {
     this._heightService.resize();
  }
}

您是否正在挂接resize事件?尽管AfterViewInit无法工作,但我需要加载所有内容,而不是在视图启动时调用