• Angular发送广播和接收广播


    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();//取消订阅
    }

    }


  • 相关阅读:
    vue 之循环添加不同class
    小程序 之使用HMACSHA1算法加密报文
    微信小程序 之wx.getLocation()获取地理信息中的小坑
    js 时间戳与yyyy-mm-dd或yyyy-MM-dd HH-mm-ss互相转换
    小程序 之登录 wx.login()
    打开串口(COM)号大于9时报错
    linux的mysql权限错误导致看不到mysql数据库
    Nginx报错汇总
    获取磁盘总空间和剩余空间
    关于CoCreateInstance的0x800401f0问题
  • 原文地址:https://www.cnblogs.com/zxg-6/p/8533256.html
Copyright © 2020-2023  润新知