欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Angular5集成eventbus的示例代碼

 更新時(shí)間:2018年07月19日 09:11:21   作者:是小太陽呀  
這篇文章主要介紹了Angular5集成eventbus的示例代碼,小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧

1.package.json中

"dependencies": {
   ...
  "vertx3-eventbus-client": "3.5.2",
 },

然后  npm install,或者:

npm install vertx3-eventbus-client@3.5.2

2.angular-cli.json中

 "scripts": [
     ...
    "../node_modules/vertx3-eventbus-client/vertx-eventbus.js"
   ],

3.創(chuàng)建一個(gè)eventbus.service.ts用來通信

導(dǎo)入eventbus:

import { EventBus } from 'vertx3-eventbus-client';

聲明eventbus:

declare var EventBus: any;

4.創(chuàng)建eventbus實(shí)例,監(jiān)聽接口以及發(fā)送消息

//創(chuàng)建實(shí)例
var eb = new EventBus('http://localhost:8080/eventbus');

eb.onopen = function() {
 //注冊(cè)監(jiān)聽器用來接受消息
 eb.registerHandler('some-address', function(error, message) {
  console.log('received a message: ' + JSON.stringify(message));
 });

 //發(fā)送消息
 eb.send('some-address', {name: 'tim', age: 587});

}

更多信息請(qǐng)參考這里 https://vertx.io/docs/vertx-web/java/

注:

對(duì)于需要發(fā)送消息來接受的消息,需要先監(jiān)聽,然后再發(fā)送消息。
對(duì)于一直推送的消息,不需要發(fā)送。

代碼實(shí)例如下:

RegisterHandler(key, id, callback) {
    const address = '***.' + key + '.' + id;
    if (typeof (this.eventBus[key]) === 'undefined' || !this.eventBus[key]) {
      this.eventBus[key] = new EventBus(environment.eventbusUrl);
    }
    if (this.eventBus[key].state === EventBus.OPEN) {
      this.eventBus[key].registerHandler(address, callback);
    } else {
      const $this = this;
      this.eventBus[key].onopen = function () {
        $this.eventBus[key].registerHandler(address, callback)
      }
    }
  }

Send(key, id) {
    var data = '';
    const address = ***.' + key + '.' + id;
    if (typeof (this.eventBus[key]) === 'undefined' || !this.eventBus[key]) {
      this.eventBus[key] = new EventBus(environment.eventbusUrl);
    }
    if (this.eventBus[key].state === EventBus.OPEN) {
      this.eventBus[key].send(address, data)
    } else {
      const $this = this;
      this.eventBus[key].onopen = function () {
        $this.eventBus[key].send(address, data)
      }
    }
  }

closeEventBus(key) {
    if (typeof (this.eventBus[key]) !== 'undefined' && this.eventBus[key] && this.eventBus[key].state === EventBus.OPEN) {
      this.eventBus[key].close();
    }
    this.eventBus[key] = null;
}

在組件ngOnDestroy中調(diào)用closeEventBus關(guān)閉eventbus。

以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。

相關(guān)文章

最新評(píng)論