我正在处理将通过其他网站上的iframe交付的Angular 2应用程序。在测试时我注意到,当我加载应用程序时,应用程序组件ngOnInit()
函数被调用两次。Angular 2应用程序组件ngOnInit在使用iframe时调用了两次
我发现这很奇怪,因为当我测试应用程序'自己'时,即不是通过iframe应用程序组件ngOnInit()
只被调用一次。
根据this answer这可能发生在子组件中的错误。但在我的情况下,我在运行应用程序'正常'时没有问题。
示例代码:
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'my-app',
template: `<h1>My App!</h1>`
})
export class AppComponent implements OnInit {
constructor() {
console.log('App Component constructor()');
}
ngOnInit() {
console.log('App Component ngOnInit()');
}
}
I帧测试:
<!DOCTYPE html>
<html>
<body>
<h1>My Test Page</h1>
<!-- iframe accessing my-app component -->
<iframe id="test-iframe" src="/#/" width="100%" height="1300px"></iframe>
</body>
</html>
我测试过的应用程序,只有一个AppComponent
,以确保没有子组件导致的任何问题。
控制台输出:
我认为这种行为很正常,因为iframe像浏览器一样行为并重新创建文件,因此你的组件重新初始化。 –
好吧,但是如果你有一个带有一个显示Angular App的iframe的页面,就像上面显示的iframe测试一样,不应该'AppComponent'被触发一次吗? 如果我在两个地方显示“my-app”组件,我会理解它。 –
您是否使用像