如何在 Angular 2 中再次调用 ngOnInit()?

How to call ngOnInit() again in Angular 2?

请在这段代码中说明,当我调用另一个方法时如何再次调用ngOnInit()

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

ngOnInit 创建组件后调用。所以你可以创建一个函数并再次调用该函数。这是示例代码。

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

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

private callFun(){
   // do code
}

您应该不需要再次调用 ngOnInit。所以问题仍然存在,你真正想要完成的是什么?您在检索路由参数时遇到问题吗?

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

您在上述订阅中的代码将在每次路由参数更改时自动重新执行。所以不需要再手动调用ngOnInit

这只是一个函数...

ngOnInit() {}

secondMethod() { this.ngOnInit(); }

我一直在这样做以重新加载我的数据,从来没有遇到过问题。

在我看来有两种选择:

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

如果目的是在更新查询参数时触发ngOnInit(),则执行以下操作:

import { Router } from '@angular/router';
constructor(private router: Router) {
    this.router.routeReuseStrategy.shouldReuseRoute = () => false;
}