兄弟组件间通信,在service 中定义 Subject,组件ngOnInit() 初始化监听;
1 service.ts 文件
import { Subject } from 'rxjs';
subjectChartResize = new Subject<string>();
2 监听组件中 component.ts
import { Subscription } from 'rxjs';
import { TestService } from './../../test.service';
subMsgResize: Subscription;
constructor(private testService: TestService) {}
ngOnInit() {
this.subMsgResize = this.testService.subjectChartResize.pipe(debounceTime(500)).subscribe(() => {
this.chartResize();
});
// pipe(debounceTime(500)) 延迟500毫秒
// 也可以写成
//this.subMsgResize = this.testService.subjectChartResize.subscribe(() => {
// this.chartResize();
//});
}
// 重绘图表
chartResize() {
this.chart.resize();
}
// 取消监听
ngOnDestroy(): void {
this.subMsgResize.unsubscribe();
}
3 另一个组件中发送消息
import { TestService } from './../../test.service';
constructor(
private testService: TestService,
) {}
// 触发通信
resize() {
this.testService.subjectChartResize.next();
}