如何在点击后重置区块中的数据?

huangapple go评论64阅读模式
英文:

How to reset data in block after click?

问题

当用户点击“加载新数据点击”时,它会在模板中显示数据。如何在下一次点击之前清除旧数据,直到新数据到来?
另外,在点击“打开卡片点击”按钮后,它会消失。

我在 stackblitz 中尝试了一下。

英文:

When user clicks "Load new data click" it displays data in template. How to clear old data after next click until data coming?
Also after click the button "Open card click" is disapered.

I tried in stackblitz

答案1

得分: 1

以下是翻译好的部分:

关于我,你已经为简单的事情创建了过于复杂的代码。
为你的情况修复只会增加更多复杂性。
我建议你重新审视所有的代码。

现在说说问题本身。解决方案是使用一个单独的变量或热可观察对象(subject)。例如 isLoading: booleanisLoading$: BehaviorSubject<boolean>(false)。在我看来,在这种情况下,只需要一个变量就足够了。关键是你需要能够从外部控制它。使用普通的 Observable 无法做到这一点。
然后,在你的 load 函数开始时,只需将这个值更改为 true。在你的可观察对象完成后,你可以将它设置为 false。使用 RxJS 中的 finalize 操作符非常适合这个任务。然后,你可以根据这个值控制模板部分的可见性。

另外,我建议你在 TS 层面合并你的可观察对象,而不是在 HTML 中。在我看来,这样更易读,可以保持模板更清洁。甚至我会将你的 state 条目保留在不同的类变量中。考虑使用 combineLatestforkJoin 等操作符,一次性获取你的可观察对象的结果。正确的操作符选择取决于你的实际代码。

英文:

As for me, you have made too much complicated code for simple things.
Fix for your case just will add more complication.
I would recommend you to rework all that code.

Now about the issue itself. The solution is to have a separate variable or hot observable (subject). for example isLoading: boolean or isLoading$: BehaviorSubject<boolean>(false). As for me in this case, just a variable is enough. The main point is that you need to have the ability to control it from the outside. You can not do that with the regular Observable.
Then at the start of your load function, you just change this value to true. And after your observable(s) is/are finalized you can make it false.finalize pipe from RxJS is nice for that. Then you can control the visibility of template parts depending on this value.

Also, I would advise you to merge your observables at TS level instead of HTML. As for me, it is much more readable and you will keep the template cleaner. I even would keep your state entries in different class variables. Consider using combineLatest, forkJoin etc, to get the results of your observables at once. The right pipe choice depends on your real code.

huangapple
  • 本文由 发表于 2023年5月7日 04:27:36
  • 转载请务必保留本文链接:https://go.coder-hub.com/76190989.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定