2017-09-26 47 views
0

更新所有组件中更新的服务值,我们有两个组件共享相同的服务,我们更改了一个组件中的服务值,这也是我需要更新其他组件的值。如何使用angular2

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

+0

使用[events](https://angular.io/api/core/EventEmitter) – Igor

回答

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

+0

如果我尝试在两个组件中都显示{{title}}即时变空。我调用“change()方法的标题值只更新在一个组件不是两个 – CodeMan

+0

我觉得是”this.configurationService.toggle.subscribe(value => this.title = value);“它不能正常工作 – CodeMan