How to call ngOnInit() again in Angular 2?
If the purpose is to trigger ngOnInit()
when query param is updated, then do following:
import { Router } from '@angular/router';
constructor(private router: Router) {
this.router.routeReuseStrategy.shouldReuseRoute = () => false;
}
There are two options from my point of view:
Calling ngOnInit() from another function scope. But I would suggest to do not adopt this approach given
ngOnInit
is an angular core method that belongs to OnInit Interface.
public ngOnInit() {
this.route.params.subscribe((params: Params) => {
this.model=this.userData;
});
}
update() {
this.ngOnInit();
}
Break your functionality into another function, use
ngOnInit
to call it and, afterwards, any request can be made from anywhere by calling the function in the following manner:this.<MethodName>();
.
public ngOnInit() {
this.getRouteData();
}
update() {
this.getRouteData();
}
getRouteData() {
this.route.params.subscribe((params: Params) => {
this.model=this.userData;
});
}