0

we have two components shared same service, we change the service value in one component that value i need to update other component also.

app.component.ts

import { Component } from '@angular/core';
import {ConfigurationService} from './first.servvice';


@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css'],
  providers : [ConfigurationService]
})
export class AppComponent {
  title : boolean;
  constructor(private configurationService:ConfigurationService){
    this.title = this.configurationService.toggle;
  }


}



@Component({
  selector: 'app-root1',
  templateUrl: './app.component1.html',
   providers : [ConfigurationService]
})
export class AppComponent1 {
  title : boolean;
  constructor(private configurationService:ConfigurationService){
      this.title = this.configurationService.toggle;
  }
  change(){
    this.configurationService.toggle = ! this.configurationService.toggle;
    this.title = this.configurationService.toggle;
  }
}

Service .ts

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

@Injectable()
export class ConfigurationService {
 toggle :boolean = false;
}

i need to update the service value when we update the service value in other components also.

Code:

https://plnkr.co/edit/LtrflSk7bICMC2xmacS5?p=preview

CodeMan
  • 1,941
  • 6
  • 26
  • 44

1 Answers1

0

Make use of the rxjs Subject. In your service, do the following change:

import {Subject} from "rxjs";

@Injectable()
export class ConfigurationService {
    toggle: Subject<boolean> = new Subject<boolean>();
}

.. and wherever you are using this value from service, subscribe to the toggle:

this.configurationService.toggle.subscribe(value => this.title = value);

.. when you want to change/update it, then you can do the following:

this.configurationService.toggle.next(!this.configurationService.toggle);

Link to you updated plunker.

FAISAL
  • 33,618
  • 10
  • 97
  • 105
  • If i am try to display the {{title}} in both component im getting empty . After i called "change() method title value only updated in one component not for two – CodeMan Sep 26 '17 at 10:40
  • what i feel is "this.configurationService.toggle.subscribe(value => this.title = value);" it is not working properly – CodeMan Sep 26 '17 at 10:42