Angular 2 App Component ngOnInit called twice when

2019-07-09 13:41发布

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:

enter image description here

1条回答
一夜七次
2楼-- · 2019-07-09 14:31

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.

查看更多
登录 后发表回答