简体   繁体   中英

Angular 5 Update Variable From Shared Data

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 :(

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM