home.module.ts
import {BroadcastService} from "../broadcast.service";
@NgModule({
imports: [
],
declarations: [
],
entryComponents: [
],
providers: [BroadcastService],//全局提供BroadcastService
schemas: [CUSTOM_ELEMENTS_SCHEMA]
})
export class GatewayPortalHomeModule {
}
/*发送广播Service*/
BroadcastService.component.ts
import {Injectable, EventEmitter} from "@angular/core";
@Injectable()
export class BroadcastService {
constructor() {}
eventbus: EventEmitter<any> = new EventEmitter<any>();
}
/*发送广播组件*/
broadcast.component.ts
import {BroadcastService} from "../broadcast.service";
@Component({
selector: 'jhi-broadcast',
templateUrl: './broadcast.component.html',
styleUrls: ['./broadcast.component.css'],
providers: [],
})
export class BroadcastComponent implements OnInit {
constructor(public broadcastService: BroadcastService){}//BroadcastService只注入不提供(providers)
ngOnInit() {}
send(){//发送广播事件
this.broadcastService.eventbus.emit({msg: 'reload'})//发送广播
}
/*接收广播组件*/
receive.component.ts
import {BroadcastService} from "../broadcast.service";
@Component({
selector: 'jhi-receive',
templateUrl: './receive.component.html',
styleUrls: ['./receive.component.css'],
providers: [],
})
export class ReceiveComponent implements OnInit,OnDestroy {
testSub: any;
constructor(public broadcastService: BroadcastService){//BroadcastService只注入不提供(providers)
this.testSub = this.broadcastService.eventbus.subscribe((event) => {//接收广播-----最好放在构造方法里
if(event.msg=="reload"){
//接收广播后做代码逻辑处理
}
});
}
ngOnInit() {
}
ngOnDestroy() {
this.testSub.unsubscribe();//取消订阅
}
}