0
votes

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

1 Answers

1
votes

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!