1

I am having a strange issue in angular (v.10). The scenario is as below.

When I load a URL by js or routeLink eg: 'this.router.navigate(['/test']); the test component calls the constructor or ngOnInit only once.This behavior is normal and there is no issue with that.( This I have verified it by console.log).

But the issue is , when I reload/refresh the URL eg: 'http://localhost:4200/#/test', the test component class will be calling the constructor/ngOnInit two times. (console.log printing the content two times).

This issue is with all the routes, and happens only when the page is reloaded.

Here are my code details.

app.component.html

<router-outlet></router-outlet>

app-routing.module.ts

{
    path: 'test',
    component: TestComponent
},

test-component.ts

export class TestComponent {
    
    constructor(){
        //this will print two times only when page reload/refresh
        console.log("test");
    }
}

I could not find out the root cause of the issue. I will provide more details if needed.

2
  • It would be better if we have full picture of your routing module or even better to share a stackblitz.com Commented Sep 4, 2020 at 10:21
  • some hints : 1) check-out what's happening in the network tab of your browser / fiddler 2) Are you using the {provide: LocationStrategy, useClass: HashLocationStrategy} or RouterModule.forRoot(routes, { useHash: true }) ? 3) Try to use another local server (eg:http-server) Commented Sep 6, 2020 at 10:25

2 Answers 2

1

After so many tries, I found the issue. I was using HMR(hot module replacement) in my angular project, which causes the components initialising twice on page reload. I have disabled HMR and is now working fine.

Sign up to request clarification or add additional context in comments.

1 Comment

How did you disable HMR? I am facing the same issue, would really appreciate some help.
0

I had a similar issue. ngOnInit was called twice, and there were two instances of angular services that should be singleton.

In my (quite specific) case, the issue was not related to HMR (hot module replacement), but to the fact that the current page was also loaded in an iframe on the same page. The iframe was related to openid-connect silent login.

As the page was also loaded in an iframe, everything was loaded twice (once in the main page, once in the iframe), and thus the console.log appeared twice.

Posting just in cases someone has the same "error".

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.