繁体   English   中英

使用iframe时,Angular 2 App组件ngOnInit调用了两次

[英]Angular 2 App Component ngOnInit called twice when using iframe

我正在研究Angular 2应用程序,该应用程序将通过其他网站上的iframe交付。 在测试的同时,我注意到当我加载应用程序时,App Component ngOnInit()函数被调用了两次。

我发现这很奇怪,因为当我“独自”测试应用程序时,即不是通过iframe调用应用程序组件ngOnInit()一次。

根据此答案,这可能由于子组件中的错误而发生。 但就我而言,“正常”运行应用程序时没有问题。

示例代码:

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测试:

<!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测试了该应用程序,以确保没有子组件引起任何问题。

控制台输出:

在此处输入图片说明

据我了解,最有可能的问题是,由于在@Component完成加载后调用了ngOnInit()方法,因此iframe元素的加载就在ngOnInit()生命周期结束后ngOnInit()开始,导致iframe src值为null。

这意味着,由于iframe在ngOnInit()之后正在加载自身,因此来自组件的任何src值都将对其不ngOnInit() ,因此为null

注意: Iframe就像注入DOM的外部浏览器一样,因此它有自己的加载时间。

因此,我建议对此类事情使用constructor(){} ,因为在实例化类时总是调用该函数。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM