Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to call ngOnInit() again in Angular 2?

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();
}
like image 927
Krunal Avatar asked Jul 06 '17 07:07

Krunal


People also ask

How do I call ngOnInit from another component?

The short answer is to use ViewChild to call the function on component B.

How many times ngOnInit is called?

ngOnInit and Constructor are called twice.


4 Answers

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;
      }); 
    }    
like image 147
mayur Avatar answered Oct 09 '22 08:10

mayur


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;
}
like image 41
Hari Das Avatar answered Oct 09 '22 07:10

Hari Das


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
}
like image 4
Tushar Ghosh Avatar answered Oct 09 '22 09:10

Tushar Ghosh


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.

like image 4
DeborahK Avatar answered Oct 09 '22 09:10

DeborahK