I was wondering how you should structure an app which makes calls to a backend.
Wrapping HTTP calls in a service seems like a natural way to do things, but how / where do you keep the data for consistency? E.g. I have a component which displays some kind of Todo list, which is retrieved from the backend OnInit
. Now when routing away from this component and routing back again all its data is reset. Of course, you could call the backend again, but wouldn't it be more beneficial to keep the data in some kind of service (even the HTTP service) for further use?
To further clarify:
class Service {
storedData: number[] = []
allObjects: BehaviorSubject<any> = new BehaviorSubject()
...
getObj(id) {
if (!this.storedData.includes(id)) {
this.getDataFromServer(id)
}
return this.allObjects.pipe(
map(objects => objects.find(obj => obj.id === id)),
filter(obj => obj && true)
)
}
getDataFromServer(id) {
return this.http.get(id).pipe(
tap(obj => {
this.storedData.push(id)
this.allObjects.put(id, obj)
})
)
}
}
Would this be a viable approach or are there other ways of handling such situations?
Furthermore, what would be the best way to go for using an object which needs multiple services to fill all its fields. (Obj: {a: number, b: number}
, a
is retrieved by AService
and b
by BService
).
Where would you store these objects (Injecting AService
in BService
and storing it in BService
/ injecting both into a third service which provides the data to requesting components)?
And what would be the best way of storing it?