[英]How to call ngOnInit() again in Angular 2?
Please explain in this code, how to call ngOnInit()
again when I call another method?请在这段代码中解释,当我调用另一个方法时如何再次调用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();
}
There are two options from my point of view:从我的角度来看,有两种选择:
Calling ngOnInit() from another function scope .从另一个函数范围调用 ngOnInit() 。 But I would suggest to do not adopt this approach given
ngOnInit
is an angular core method that belongs to OnInit Interface .但我建议不要采用这种方法,因为ngOnInit
是属于 OnInit Interface 的角度核心方法。
public ngOnInit() {
this.route.params.subscribe((params: Params) => {
this.model=this.userData;
});
}
update() {
this.ngOnInit();
}
Break your functionality into another function, use
ngOnInit
to call it and, afterwards, any request can be made from anywhere by calling the function in the following manner:this.<MethodName>();
将您的功能分解为另一个函数,使用ngOnInit
调用它,之后,可以通过以下方式调用该函数从任何地方发出任何请求:this.<MethodName>();
. .
public ngOnInit() {
this.getRouteData();
}
update() {
this.getRouteData();
}
getRouteData() {
this.route.params.subscribe((params: Params) => {
this.model=this.userData;
});
}
If the purpose is to trigger ngOnInit()
when query param is updated, then do following:如果目的是在更新查询参数时触发ngOnInit()
,则执行以下操作:
import { Router } from '@angular/router';
constructor(private router: Router) {
this.router.routeReuseStrategy.shouldReuseRoute = () => false;
}
ngOnInit
called once the component is created.一旦组件被创建, ngOnInit
被调用。 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
}
You should not need to call ngOnInit again.您不需要再次调用 ngOnInit。 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.所以不需要再次手动调用 ngOnInit。
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.我一直在这样做以重新加载我的数据,从来没有遇到过问题。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.