ngOnInit called everytime i change route

Viewed 1762

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 Answers

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