1

I assume, this is a very basic question, but I did not found any answer elsewhere (I think, this goes in the same direction).

I wonder, if an Angular (2 or 4) service should hold any temporary data.

To illustrate my question, lets assume within the Tour of Heroes, after having fetched the heroes once, I want to be able to search within them without an API-call.

I wonder, if it would make sense to add a loadAndGetHeroes(heroListId)-method to the service, which returns the list, but also saves the list within a private field in the service.

Then I could add a searchForHeroPattern(pattern)-method to the service, which does not need an API call but can search on the client and would also be available for other parts of the angular-app.

Is this an intended approach or is there a better way to implement such things?

Sebastian Werk
  • 1,568
  • 2
  • 17
  • 30
  • There's more than one way to do this. It's ok to do this like that. Another approach is to stick to observables and cache data there, like https://stackoverflow.com/a/40250950/3731501 . Any way, data that belongs to a service should be stored inside a service. – Estus Flask Sep 27 '17 at 22:17

1 Answers1

2

After looking around, I think, basically this part of the fundamentals documentation answers my question: Yes, it seems, that storing data in a private field is perfectly ok.

I am sorry for bothering. If somebody thinks, this question should better be deleted, just go on...

Sebastian Werk
  • 1,568
  • 2
  • 17
  • 30
  • Yes, I agree. Storing data in a service is perfectly fine. However, you may want to consider `@ngrx/store` - its a redux pattern for managing state centrally for you. For very complex apps with a lot of subscribers on the same page (or complex UI interactions), `@ngrx/store` is worth considering. – Michael Kang Sep 28 '17 at 06:26