Search code examples
angularrxjsangular-ui-routercomponentsstate

How can I save the state of a component after navigating to another component in Angular 8


I have 2 components: HomeComponent and CityComponent. They do not have any relationship. After navigating back to the HomeComponent, the state of the CityComponent is lost when I navigate to it again. How can I save the state? Any ideas?


Solution

  • You can use services to remember states between routes because they are usually singletons. The state Behaviour Subject can store an object which contains any states you might want to remember for you so every time the component is initialised all you have to do is retrieve the current value by .getValue() from the state$ in the service. Also, when you update any state value you should remember to update the state stored in the service.

    state.service.ts

    @Injectable({
      providedIn: "root"
    })
    export class StateService {
      state$ = new BehaviorSubject<any>(null);
    }
    

    city.component.ts

    export class CityComponent implements OnInit {
      constructor(private stateService: StateService) {}
      state: any;
      ngOnInit() {
        this.state = this.stateService.state$.getValue() || {};
      }
    
      updateFoo(val: any) {
        this.state.foo = val;
        this.stateService.state$.next(state);
      }
    

    city.component.html

    <p>{{state.foo}}</p>