angularrxjsdata-sharing

The best practice of distribution data across all Angular Universal components?


I have got a pretty big Angular SPA with router-outlets and different level components.
Currently, my application supports different regions where each region is a separate routing with relevant data attached:

{
    path: 'Saint-Petersburg', canActivate: [MetaGuard],
    loadChildren: () => import('./components/main-page/main-page.module').then(m => m.MainPageModule),
    data: { region: regions[1] }
 }

The change of a region is done via routing data and localstorage So, when a user changes a region, Angular app:
1) obtains region data from routing (here data: { region: regions[1] } )
2) updates region value in the local storage
3) reloads the application (window.reload)
4) all components check region from localstorage and provide relevant data.

The solution works fine but error-prone because:
1) I need to always read a region from localstorage
2) Data provided in the routing can only be shared with the module specified in the routing
3) Local storage is not Angular Universal friendly

Could you advise the best solution for storing a region or accessing it across all components?
Do I need to use a Service with Subjects?
Or use RxJS similar to Redux?

Please help


Solution

  • If you only need to store a region state, you could use a singleton service for that

       @Injectable({
      providedIn:"root"
    })
    export class RegionStore{
        private _region$ = new BehaviourSubject<string>();
    
        public region$(){
          return this._region$.asObservable();
        }
    
        public region(){
          return this._region$.getValue();
        }
    
        changeRegion(region:string){
          this._region$.next(region);
        }
    
    }
    

    but if you want to have application state as a whole, then you could use NGRX NGXS Akita