How to call ngOnInit() again in Angular 2?

萝らか妹 提交于 2019-11-27 16:06:13

问题


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

回答1:


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 ngOnInitis 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 ngOnInitto 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;
  }); 
}    



回答2:


It's just a function ...

ngOnInit() {}

secondMethod() { this.ngOnInit(); }

I've been doing it all the time to reload my data, never had a problem with it.




回答3:


ngOnInit called once the component is created. so you can create a function and call the function again. Here is the sample code.

ngOnInit(): void {
    this.callFun();
}    

update() {
    this.callFun();
    // do code
}

private callFun(){
   // do code
}



回答4:


You should not need to call ngOnInit again. So the question remains, what are you really trying to accomplish? Are you having issues retrieving the routing parameter?

 ngOnInit(): void {
      this.route.params.subscribe((params: Params) => {
        this.model=this.userData;
  }); 

Your code within the subscribe above will AUTOMATICALLY be re-executed every time the route parameters change. So there is no need to manually call ngOnInit again.




回答5:


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


来源:https://stackoverflow.com/questions/44942645/how-to-call-ngoninit-again-in-angular-2

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!