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

    }


  • 相关阅读:
    clientHeight、offsetHeight、scrollHeight详解
    JavaScript中常见的字符串操作函数及用法
    获取伪元素的属性和改变伪元素的属性
    HTML和CSS实现左侧固定宽度右侧内容可滚动
    gulp常用插件
    gulp入门详细教程
    Javascript 异步实现机制
    JavaScript:彻底理解同步、异步和事件循环(Event Loop)
    chrome调试,打完断点后关于JS的几个控制介绍
    js断点调试心得
  • 原文地址:https://www.cnblogs.com/zxg-6/p/8533256.html
Copyright © 2020-2023  润新知