Angular 2应用程序组件ngOnInit在使用iframe时调用了两次 [英] Angular 2 App Component ngOnInit called twice when using iframe
问题描述
我正在开发一个Angular 2应用程序,该应用程序将通过其他网站上的iframe提供。测试时我注意到,当我加载应用程序时,App Component ngOnInit()
函数被调用两次。
我发现这很奇怪,因为当我在它自己上测试应用程序时,即不是iframe,App Component ngOnInit()
只被调用一次。
根据
据我了解,问题很可能就是,因为在 @Component
完成加载后调用 ngOnInit()
方法,所以iframe元素的加载开始于之后 ngOnInit()
生命周期结束,导致iframe src
值为null。
这意味着因为iframe在调用 ngOnInit()
之后加载自己,所以 src
来自组件的值对它来说是陌生的,因此 null
。
注意: iframe就像注入DOM的外部浏览器一样,因此它有自己的加载时间。
所以我建议使用构造函数(){}
来处理这类事情,因为在实例化类时它总是被调用。
I'm working on an Angular 2 application that will be delivered via an iframe on other websites. Whilst testing I've noticed that when I load the application the App Component ngOnInit()
function is being called twice.
I'm finding this weird because when I'm testing the application 'on it's own', i.e. not though an iframe the App Component ngOnInit()
is only called once.
According to this answer this could happen due errors in child components. But in my case I'm not having the problem when running the application 'normally'.
Example Code:
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()');
}
}
Iframe Test:
<!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>
I've tested the application with only an AppComponent
to be sure that no child components are causing any issues.
Console Output:
From my understanding, most likely the problem is, since the ngOnInit()
method is called after the the @Component
finishes loading, the iframe element's loading begins right after the ngOnInit()
life cycle finishes causing the iframe src
value to be null.
That means since the iframe is loading its self after the ngOnInit()
is called, anysrc
value coming from the components would be foreign to it, hence null
.
Note: Iframe is like an outside browser injected in to DOM, so it has its own loading time.
So I would suggest using the constructor(){}
for this kinds of things since its always called when the class is instantiated.
这篇关于Angular 2应用程序组件ngOnInit在使用iframe时调用了两次的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!