angular 基于rxjs的Subject全局广播监听
- 创建服务my.observer.service.ts
import { Subject } from 'rxjs';
import { OaItem } from '../api/settingApi.service'; // 范型接口, 可不设置接口,
// 不过最好养成写接口约束的习惯,有利于开发
oaInfo = new Subject<OaItem>();
- 要暴露的文件内:
import { OaItem } from '../../api/settingApi.service';
import { MyObserverService } from '../../service/my.observer';
changeOa(event: OaItem): void {
this.myObserver.oaInfo.next(event);
}
- 你要监听的组件中:
import { MyObserverService } from '../../service/my.observer';
ngOnInit(): void {
this.myObserver.oaInfo.subscribe( res => {
this.currentOa = res;
});
}
- 为了防止其他页面访问到该方法,一般会添加防抖
ngOnInit(): void {
if (observerOpen) {
this.myObserver.oaInfo.subscribe( res => {
this.currentOa = res;
});
}
}
ngOnDestroy() {
this.observerOpen = false;
}