【发布时间】:2018-03-07 12:10:45
【问题描述】:
我们有两个组件共享相同的服务,我们更改了一个组件中的服务值,该值我也需要更新其他组件。
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;
}
当我们更新其他组件中的服务值时,我需要更新服务值。
代码:
【问题讨论】:
-
使用events
标签: angular angular2-services angular2-directives