Please explain in this code, how to call ngOnInit()
again when I call another method?
ngOnInit(): void {
this.route.params.subscribe((params: Params) => {
this.model = this.userData;
});
}
update() {
this.loading = true;
this.userService.update(this.model).subscribe(
(data) => {
alert('Update successful');
},
(error) => {
alert('Not updated');
this.loading = false;
},
);
this.user_data();
}
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;
});
}