如何在Angular 2中再次调用ngOnInit()? [英] How to call ngOnInit() again in Angular 2?

查看:589
本文介绍了如何在Angular 2中再次调用ngOnInit()?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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:

从另一个函数作用域调用ngOnInit().但是我建议不要采用这种方法,因为ngOnInit 是属于OnInit接口的角核方法.

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

将您的功能分解为另一个功能,使用ngOnInit进行调用,然后,可以通过以下方式调用该功能,从而从任何地方发出任何请求:this.<MethodName>();.

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

这篇关于如何在Angular 2中再次调用ngOnInit()?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆