3
votes

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]);
    }
}
2
Not sure if I understand your question, but that's the expected behavior? You change the route, and you return back the component is a new instance of TestListComponent so OnInit() call is expected. - penleychan
It should be called only once as i know when the TestListComponent is created not every time when i come back to same component. Am i right? - Vikram Singh
I think we answered it pretty well... It's a new instance every time component is called - penleychan
I think Vikram you are getting confused here. @12seconds last reply was for It should be called only once as i know when the TestListComponent is created not every time when i come back to same component. Am i right? and not component is created every time when we change the route?. - Aakash Thakur
1In testService.getTest(), have you mapped an Response to a json payload as Array<Test>? <Array<Test>>data .... is the outer <> necessary? if your return type is as I suggested this.testList = data would suffice - JGFMK

2 Answers

2
votes

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

0
votes

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');
}