I have a controller implements OnInit The problem here is whenever i change the route and come back to same component ngOnInit is called everytime. What i am doing wrong i am not able to understand.Anybody please help me.
@Component({
selector:'test-list',
templateUrl:'./testlist.component.html',
styles:[`.testname{
text-transform : capitalize;
}`]
})
export class TestListComponent implements OnInit{
testList:Array<Test>;
constructor(private testService:TestService,private router:Router){}
ngOnInit(){
this.testService.getTest()
.subscribe(
data=>this.testList = <Array<Test>>data,
error=>alert(error)
);
console.log("ngInit")
}
editTest = (id)=>{
this.router.navigate(['createtest',id]);
}
}
ngOnInit()
is executed everytime the component is loaded. It doesn't need to be called. This is a lifecycle hook for doing initial stuff. You can learn more about angular lifecycle hooks here
If in the constructor you subscribe to the active route, ngInit will be called every time the router navigates to that page.
constructor(
private route: ActivatedRoute,
private router: Router
) {
this.route.queryParams.subscribe(async (params) => {
if (this.router.getCurrentNavigation().extras.state) {
// TODO save the params
}
});
}
ngOnInit(){
console.log('ngOnInit called');
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.