Angular 2 App Component ngOnInit called twice when using iframe

拟墨画扇 提交于 2019-12-12 18:19:04

问题


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:


回答1:


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.



来源:https://stackoverflow.com/questions/40783511/angular-2-app-component-ngoninit-called-twice-when-using-iframe

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!