简体   繁体   English

强制角度6组件重新加载

[英]Force an angular 6 component to reload

Is there any way of forcing an angular component to reload? 有什么方法可以迫使角组件重新加载吗? What I mean by this is, I want everything in my actual component to die, and load again from zero, with it's constructor, ngOnInit() and everything. 我的意思是,我希望我的实际组件中的所有组件消失,并使用其构造函数ngOnInit()和所有组件从零重新加载。

The I want to do this because I have an app that fetches a lot of data using promises. 之所以要这样做,是因为我有一个应用程序可以使用Promise提取大量数据。 The data that is fetched depends on some parameters that are controlled by the user within the app. 提取的数据取决于应用内用户控制的某些参数。

When these parameters change, the app fetches data again. 这些参数更改后,应用程序将再次获取数据。 The problem is: if the last promises haven't ended by the time the parameters are changed, new data is starting to get fetched, but the old promises are still waiting to finish. 问题是:如果在更改参数时最后的承诺尚未结束,则将开始获取新数据,但是旧的承诺仍在等待完成。 Plus when they complete, they display wrong information for a couple of seconds. 另外,完成操作后,它们会显示错误的信息几秒钟。 Also, if the new promises finish sooner than the old promises, the app displays the correct information for a few seconds until the old promises end, and then displays wrong information until the parameters are changed again. 此外,如果新的承诺比旧的承诺早完成,则该应用会显示正确的信息几秒钟,直到旧的承诺结束,然后显示错误的信息,直到再次更改参数。

Reloading the component is not the appropriate fix for the problem. 重新加载组件不是解决该问题的适当方法。 Just learn how to use observables, which have everything to deal with such problems (or hack something with promises, but you'd better use observables, since they're precisely designed to make such things easier). 只需学习如何使用可观察变量,它具有处理此类问题的所有内容(或破解某些承诺,但是您最好使用可观察变量,因为它们是专门为简化此类操作而设计的)。 For example: 例如:

userInput.valueChanges.pipe(
  switchMap(input => this.someService.getData(input))
).subscribe(data => this.displayData(data));

Explanation: every time the user input changes, you call the service to get the data, and then display it. 说明:每次用户输入更改时,您都会调用服务以获取数据,然后将其显示。 If the user input changes and you still haven't got the data, the subscription to the previous data observable is automatically cancelled, and a new subscription to the new data observable is created. 如果用户输入发生更改,但您仍然没有数据,则自动取消对先前可观察数据的订阅,并创建对新可观察数据的新订阅。

You can do it with routing. 您可以通过路由来做到这一点。 Inside ngOnInit() of a componenet you could redirect to a component that you want to reload. 在componenet的ngOnInit()内部,您可以重定向到要重新加载的组件。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM