2017-09-26 71 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