0
votes

I am building a Angular app and I am having some trouble understanding RxJs and how to use it to solve my problem.

Let's say I have a component that requires 2 objects of type Item

export class TemplateComponent {

    private item1: Item;
    private item2: Item;

    constructor(private store: ItemStore) {

    }
}

and the Item class

export class Item {
    name: string;
    value: string;
}

as you can see, I also have a datastore for Items

export class ItemStore {
    public subscribedItems: Item[];

    constructor(private httpService: ItemHttpService) {

    }

    public getSubscribedItems() {
        this.httpService.getItems(this.subscribedItems)
            .subscribe(response => {
                this.subscriberItems = response;
            }
    }
}

The ItemStore has a Service injected into it that calls an API to get items.

The idea is to have a list of subscribed Items that needs to be updated from the API, so each component that needs bindings to Items can add their items to the subscribedItems array, and the store will get the new Items from the API continually. The Items are really sensor data so their value can vary over time, but their name stays the same

Is there a smart solution that lets my TemplateComponent subscribe to changes in only item1 and item2 and not care about the rest of the items, or do I need to subscribe to the subscribedItems array and then filter my way through it to get the new values for item1 and item2?

1
So basically, let me see if I understood it, you would have a list of items that will receive updates periodically, and from a specific component you would like to get updates for let's say item 2 and 4 of the array? What happens to the rest of the items? Do they also get updated even though they're not being "requested" by other components? Or you want to get them receiving updates only when a component requests them? - Osman Cea
Only the items that are currently being used in a "open" component should be requested, when the component i destroyed, the subscription of those items should be completed, if they are not also watched by another open component. - Ingemar Skelander

1 Answers

0
votes

To solve your problem you should use WebSocket technology. Great example of how to do this is described here Angular WS