我对此问题有同样的问题:
Share data between components using a service in Angular2
但它不会起作用,因为我认为将服务注入两个组件意味着服务类有两个实例。因此,尝试修改服务中组件的数据,并查看其他组件中的更改仍无法正常工作。这是什么解决方案?
注意:
我在评论中尝试了解决方案,但仍无法正常工作......
这是我的服务:
import { Injectable } from '@angular/core';
@Injectable()
export class TestService {
counter: number = 0 ;
constructor() {
console.log('instanciate Test Service' + this.counter ) ;
this.counter ++ ;
}
setCounter(counter: number){
this.counter =counter ;
console.log('new value of counter is ' + this.counter );
}
}
第一个组成部分:
@Component({
selector: 'rb-test',
templateUrl: './test.component.html',
styleUrls: ['./test.component.css']
})
export class TestComponent implements OnInit , OnChanges ,DoCheck{
bindingdata = 'test' ;
data: number;
constructor(public _ts: TestService) {
}
ngOnChanges(){
this.data=this._ts.counter ;
console.log('is changing');
}
ngDoCheck(){
this.data=this._ts.counter ;
console.log('is doing check');
}
ngOnInit() {
this.data = this._ts.counter;
}
}
第一个组件的模板:
{{data}}
<input type="text" [(ngModel)]="bindingdata" />
第二部分:
@Component({
selector: 'rb-other-test',
templateUrl: './other-test.component.html',
styleUrls: ['./other-test.component.css']
})
export class OtherTestComponent implements OnInit ,OnDestroy{
data: number;
constructor(public _ts: TestService) { }
ngOnInit() {
this.data= this._ts.counter;
}
public change(){
this._ts.setCounter(7878);
this.data = this._ts.counter;
}
ngOnDestroy() {
}
}
第二部分的模板:
<input type="submit" value="change" (click)="change()">
{{data}}
结果: