0

In ComponentA I have a variable that gets its value from a variable in a shared data class. ComponentA looks like this:

import { SharedData } from '../../shared/shared.data';
...
export class ComponentA implements OnInit {
  TheSelectedClient = this.SharedData.SelectedClient;

  constructor(
    private SharedData: SharedData,
  ) { }

And the shared data class looks like this:

export class SharedData {
    SelectedClient = 'Client One';

But when I update the SharedData.SelectedClient = 'Client Two' from a different component, then TheSelectedClient in ComponentA doesn't update by itself. How do I make TheSelectedClient automatically update when SharedData.SelectedClient updates?

I feel like the answer is in Observables but I don't exactly understand how to use it. I tried reading up on it but it is hard to understand :(

Frank
  • 2,109
  • 7
  • 25
  • 48
  • For that you can use `@Input` and `@Output` decorators with `EventEmitter` in order to capture the change in child, or you can use `@ViewChild`. Take a look at [this](https://stackoverflow.com/questions/43274721/angular2-difference-between-decoraters) answer for distinction between decorators. – mutantkeyboard May 07 '18 at 12:19
  • I know about these but are these not bad practice? – Frank May 07 '18 at 12:20
  • You can use `Subject` and `Observable` like explain in the Angular official guide : https://angular.io/guide/component-interaction#parent-and-children-communicate-via-a-service – Neyt May 07 '18 at 12:29

2 Answers2

1

You need to create observable and subscribe to its value when changes occured. Try this -

import { BehaviorSubject } from 'rxjs/BehaviorSubject';

export class SharedData {
    private SelectedClient = new BehaviorSubject(any);
    SelectedClientObs = this.SelectedClient.asObservable();

    SelectedClientCall(updatedValue) {
      this.SelectedClient.next(updatedValue);
    }
}

import { SharedData } from '../../shared/shared.data';

export class ComponentA implements OnInit {
  TheSelectedClient : null;

  constructor(
    private SharedData: SharedData,
  ) { 
    this.SharedData.SelectedClientObs.subscribe(res => {
      // Here you get the update value
      this.TheSelectedClient = res;
    }); 
  }

For more information you can refer official documentation for the same here

Pardeep Jain
  • 84,110
  • 37
  • 165
  • 215
0

Here the component is inserted as a new object in every component.You can use service and provide it at root level(appModule) to treat as a singleton.

Thanks

Vikas Garg
  • 202
  • 2
  • 8