更新所有組件中更新的服務值,我們有兩個組件共享相同的服務,我們更改了一個組件中的服務值,這也是我需要更新其他組件的值。如何使用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
使用[events](https://angular.io/api/core/EventEmitter) – Igor