zoukankan      html  css  js  c++  java
  • 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();//取消订阅
    }

    }


  • 相关阅读:
    【bzoj4066】 简单题
    【bzoj1941】 Sdoi2010—Hide and Seek
    【bzoj2648】 SJY摆棋子
    【poj2154】 Color
    【poj2409】 Let it Bead
    【codevs1106】 篝火晚会
    【poj3270】 Cow Sorting
    【bzoj1004】 HNOI2008—Cards
    【bzoj3143】 Hnoi2013—游走
    【codeforces 749E】 Inversions After Shuffle
  • 原文地址:https://www.cnblogs.com/zxg-6/p/8533256.html
Copyright © 2011-2022 走看看