'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 1:[1]

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>

Solution 2:[2]

you should read about app routing components. Basically you should have a file app-routing.modul.ts here is the official angular link.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Orace
Solution 2 Sam