0
votes

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.

1
It would be better if we have full picture of your routing module or even better to share a stackblitz.com - StPaulis
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) - christophe.chapron

1 Answers

0
votes

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.