如何使用angular2更新所有组件中的更新服务值

时间:2017-09-26 10:09:18

标签: angular angular2-services angular2-directives

我们有两个组件共享相同的服务,我们在一个组件中更改了服务值,我还需要更新其他组件的值。

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;
  }
}

服务.ts

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

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

我还需要在更新其他组件中的服务值时更新服务值。

代码:

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

1 个答案:

答案 0 :(得分:0)

利用rxjs Subject。在您的服务中,请执行以下更改:

import {Subject} from "rxjs";

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

..无论您在服务中使用此值,只需订阅toggle

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

..当您想要更改/更新它时,您可以执行以下操作:

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

链接到您updated plunker