您可以使用 EventEmmiter,如下所示。
变更服务.ts
import {EventEmitter} from 'angular2/core';
export class ChangeService {
calltestTry: EventEmitter<string> = new EventEmitter();
constructor() {}
emitcalltestTryEvent(data) {
this.calltestTry.emit(data);
}
getcalltestTryEmitter() {
return this.calltestTry;
}
}
组件1.ts
@Component({
selector: 'app-component1',
})
export class ComponentOne {
item: number = 0;
subscription: any;
constructor(private changeService:ChangeService) {}
ngOnInit() {
this.subscription = this.changeService.getcalltestTryEmitter()
.subscribe(item => this.testTry(item));
}
testTry(item: string) {
console.log(item);
}
ngOnDestroy() {
this.subscription.unsubscribe();
}
}
组件2.ts
@Component({
selector: 'app-component2',
})
export class ComponentTwo {
item: number = 0;
subscription: any;
constructor(private changeService:ChangeService) {}
ngOnInit() {
}
sampleCall(item: number) {
let a = "Sravya";
this.changeService.emitcalltestTryEvent(a);
}
ngOnDestroy() {
this.subscription.unsubscribe();
}
}