How to call ngOnInit() again in Angular 2?

Krunal picture Krunal · Jul 6, 2017 · Viewed 56.4k times · Source

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

Answer

mayur picture mayur · Jul 6, 2017

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