BobtheMagicMoose
BobtheMagicMoose

Reputation: 2429

Should a component edit a copy of object from Angular service?

I am trying to make a basic transaction tracking application and have a service that tracks the transactions. I have a BehaviorSubject that holds the transactions and when a component requests the transactions, they are given an observable of the behaviorsubject.

I now am trying to make it so that the component can edit a transaction and have the service synchronize the change back to the server when an edit occurs. What is the best way to approach this? Do I somehow lock the values held by the behaviorsubject and require edits to be passed through setters? Do I only pass copies of the transactions to the components? Do I trust the components not to make edits without 'telling' the service?

What I do now is I have the components being able to edit the transactions and the service checks every 10 seconds to see if the transaction list is different than an original synched version and then send differences to the server. This doesn't seem right.

Upvotes: 0

Views: 233

Answers (3)

Adrian Brand
Adrian Brand

Reputation: 21638

Take a look at a library I have started working on called RxCache. I wrote it in response to my dislike of the current Redux store style approach that is infecting our beautiful Angular world. It gives you the push data approach without any of the ridiculous boilerplate and overhead of ngrx.

https://github.com/adriandavidbrand/ngx-rxcache

Upvotes: 1

windmaomao
windmaomao

Reputation: 7680

I actually don't really think people should jump directly to Redux whenever these topic surface.

Whatever you'd like to implement, you can still make it happen in your current service. What you should do is to lock the edits only via your service. And make your component listens to your BehaviorSubject published by your service.

You can't change the record directly in your component, because the copy you get there should be a read-only copy. This is essentially what Redux wants you to do, the difference is that Redux doesn't require you to have an extra service layer.

Upvotes: 3

The Oracle
The Oracle

Reputation: 2503

I suggest you use a state management tool like ngrx. Use store and effects. It will enable you to understand how your state changes and when you can make a service call through effects.

Also check this article for state management in angular. You could also do some findings on google.

You will come across ngrx (redux + rxjs) and redux as the most common tools used in managing state in angular.

Upvotes: 0

Related Questions