2017-09-26 3 views
0

私たちは2つのコンポーネントが同じサービスを共有している、我々は他のコンポーネントを更新する必要がある値。どのように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

[イベント](https://angular.io/api/core/EventEmitter)を使用 – Igor

答えて

0

はrxjs Subjectをご利用ください。変更したいとき/それを更新...

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

:あなたのサービスでは、以下の変更を実行します。

import {Subject} from "rxjs"; 

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

を...そして、あなたはサービスからこの値を使用しているところはどこでも、toggleを購読しますあなたupdated plunker

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

リンク:、その後、次の操作を行うことができます。

+0

私は両方のコンポーネントimが空になっている{{title}}を表示しようとしています。私は "change()メソッドのタイトル値は2つではなく1つのコンポーネントでのみ更新されました – CodeMan

+0

私は" this.configurationService.toggle.subscribe(value => this.title = value); "と感じるものが正しく動作していない – CodeMan

関連する問題