在类打字稿中使用caveniOrSubject作为类/对象成员的抗模式吗?

发布于 2025-02-08 15:19:41 字数 804 浏览 2 评论 0 原文

我正在使用Angular,并且有几个类,其成员在Angular HTML模板中显示。这些课程具有这样的常见成员:

class Foo {
    bar: string;
    bas: Date;
}

在许多情况下,我必须手动刷新FOO对象成员的视图。由于我正在使用Angular,因此我可以使用 capation ucipiourSubject 来自 =“ https://rxjs.dev/guide/overview” rel =“ nofollow noreferrer”> rxjs async 管道简化渲染检测。用行为主体替换许多类别/对象成员是反模式吗?有缺点吗?

class Foo {
    bar: BehaviourSubject<string>;
    bas: BehaviourSubject<Date>;
}

I am using Angular, and I have a couple of classes whose members I display in an Angular HTML template. These classes have common members like this:

class Foo {
    bar: string;
    bas: Date;
}

In many cases I have to manually refresh the view if members of Foo objects changed. Since I am using Angular, I could make use of BehaviourSubject from rxjs in combination with the async pipe to simplify the render detection. Is it an anti-pattern to replace many class/object members with BehaviourSubject? Is there a downside to this?

class Foo {
    bar: BehaviourSubject<string>;
    bas: BehaviourSubject<Date>;
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

故笙诉离歌 2025-02-15 15:19:41

我不确定这是反pattern的,但是您必须记住一些事情:

  • 如果需要手动触发变更检测,也许是因为您没有考虑到不变性:如果您更改了内部属性用作Onpush组件的输入的对象,更改检测不会触发。您必须为其工作分配一个新对象: this.input = {... this.input,changeprop:newValue} ;
  • 我更喜欢将主题保留在服务上(我经常使用组件提供的服务,以确保它们在移动另一个功能时会被销毁 - 我在root/module提供的服务方面遇到了保留以前的主题数据的服务),但是如果您愿意要把它们留在课堂上,请记住HTTP调用不了解它们。他们将响应转换为JSON对象(这就是为什么当我们使用日期类将属性输入响应错误时可能会发生时,因为HTTPCLCLIENT会将其视为字符串)。

我希望这会有所帮助!

I'm not sure it's an anti-pattern, but you have to remember a few things:

  • If there's a need to manually trigger change detection, maybe it's because you're not taking immutability into account: if you change an internal property of an object which is used as input for a OnPush component, change detection won't trigger. You must assign a new object for it to work: this.input = { ...this.input, changedProp: newValue };
  • I prefer to keep my subjects on services (I often use component provided services, to make sure they will be destroyed when moving to another feature - I've had problems with root/module provided services keeping previous subject data), but if you want to keep them in a class, remember HTTP calls don't understand them. They convert the response as a JSON object (which is why when we use the Date class to type a property in a response errors can happen, since HttpClient will see it as a string).

I hope this helps!

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文