Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I save data from multiple services in angular 2 across an entire application?

Here's what I'm trying to achieve: I have an application where I basically want to be able to save data from a number of services (for example, a "logger" service that contains a list of log entries; a "themes" service that contains a list of themes and / or style settings; etc...). For simplicity's sake, I'm using localStorage to save this data. As such, I have a generic "LocalStorage" service that defines members for saving and loading key/value pairs as one might expect.

My question is: From a high-level design perspective, how should I approach saving and loading my application data from a single control point (i.e. a "Save / Load" button on a settings page). Ideally I'd like to be able to implement my application services in such a way that each would implement a common "local storage" interface that would require a "Save Data" and "Load Data" method to be implemented in that service. The part I'm struggling with is how to iterate across all services that might implement this "local storage" interface and call all of their "save / load" methods at once. For that matter, I'm not even sure if this is the right approach to take.

I'm still pretty new to Angular 2, so if anyone can shed some light onto this sort of problem, and suggest a sensible solution, it would be greatly appreciated. Thanks!

like image 305
Novark Avatar asked Sep 25 '22 07:09

Novark


1 Answers

I would use a global service (might even be the LocalStorageService but I guess a more UI-specific one would be more appropriate. I use GlobalUserActions as an example:

@Injectable()
export class GlobalUserActions {
  // Subject would be better but I don't know TS/RxJS well enough
  // EventEmitter should only be used for @Output()
  saveAll:EventEmitter = new EventEmitter(); 

  doSaveAll() {
    saveAll.emit(null); // or any information that might be useful to components
  }
}
@Component({
  selector: 'any-com',
  ...
}) 
export class AnyComponent {
  constructor(
      private globalUserActions: GlobalUserActions,
      private persistenceService: PersistenceService) {
    this.globalUserActions.saveAll.subscribe(save);
  }

  save(value) {
    this.persistenceService.save(...);
  }
}
bootstrap(AppComponent, [ ... ,
    LocalStorageService, 
    // use a generic `PersistenceService` but provide a concrete
    // `LocalStorageService`
    provide(PersistenceService, {useExisting: LocalStorageService})
]); 
like image 59
Günter Zöchbauer Avatar answered Oct 16 '22 16:10

Günter Zöchbauer