I am little confused. Reading this stackoverflow question.
https://stackoverflow.com/questions/51395830/why-is-constructor-call-each-time-after-injection-of-service
Here for older version of angular they say that constructor from service is called each time it is initialized. I am using angular version 10 and by me is called just once. So my question is if anybody knows why ?
The test code that i have are two components.In their constructor's is injected the testService. And in the constructor from the testService i have just console log statement.
TEST SERVICE
import { Injectable } from '@angular/core';
@Injectable({
providedIn: 'root'
})
export class TestService {
constructor() { console.log('constructor called')};
}
HOME COMPONENT
export class HomeComponent implements OnInit {
constructor(private testService: TestService) { };
}
LAYOUT COMPONENT
export class LayoutComponent implements OnInit {
constructor(private testService: TestService) { };
}
APP COMPONENT
<a routerLink='./layout'>go to layout</a>
<a routerLink='./home'>go to home </a>
APP ROUTING MODULE
const routes: Routes = [
{ path: 'home', component: HomeComponent },
{ path: 'layout', component: LayoutComponent }
];
APP MODULE
@NgModule({
declarations: [
AppComponent,
LayoutComponent,
HomeComponent
],
imports: [
BrowserModule,
BrowserAnimationsModule,
HttpClientModule,
AppRoutingModule,
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
So, my app component is initialized. When i click on - go to home - then it redirects me to the home component.It is initialized and i see - constructor called - in the console. But when i go on layout component after that i don't see the statements in the console.
Why this time the constructor is not initialized ?
And it happens in the opposite, if i go first to layout i see console log statements and after if i go back to app component and then go to home i see nothing.