3

I am new to Angular. I am using Router for switch the screen.. Like this

this._router.navigate(['a_page'],{state: {data: moredata})

and get the state in a_page constructor like this

this._router.getCurrentNavigation().extras.state;

But if i back from a_page and then forward using browser forward button the extras.state was null. I don't know how to do this in best way, please suggest the idea. Thank you.

Sabish.M
  • 2,022
  • 16
  • 34

2 Answers2

1

You can use typescript accessor setter and getter to achieve desired result.

create a service where you set and get the value.

state.service.ts

import { Injectable } from '@angular/core';

@Injectable({
 providedIn: 'root'
})
export class SomeService {
 _state;

 get state() {
  return this._state;
 }

 set state(data) {
  this._state = data
 }
}

get and set can be achieve from any component

export class StateComponent {
 // inject state service to access set get methods
 constructor(private service: StateService) {
  this.service.state =  { data: moredata }; // setting state

  console.log(this.service.state); // getting state from anywhere 
}

Hope this works.

Kamran Khatti
  • 3,754
  • 1
  • 20
  • 31
0

You can use singleton services wi th a Subject in order to share data between components (a state management library isn't required).

Create a service using angular-cli : ng generate service service-name

Inject the service into the constructor of the components which need to share the same data :

constructor(private service: MyService) {}

Inside your service, declare a subject which will be responsible to keep the data (a BehaviorSubject is a good idea as it's initialized with a value) :

data: BehaviorSubject<any> = new BehaviorSubject<any>('foo');

To change its value from a component, use the next() method on it :

constructor(private service: MyService) {}

update(): void {
  this.service.data.next('bar');
}

Then in order to get the last value in any component (or service/directive...), subscribe to the BehaviorSubject and do whatever you want with the value :

constructor(private service: MyService) {}

ngOnInit(): void {
  this.service.data.subscribe(value => {
  // do whatever
  });
}

Each time the next() method will be used somewhere in your application, any subscription somewhere else will get this new value.

Gérôme Grignon
  • 3,859
  • 1
  • 6
  • 18