Angular5集成eventbus的示例代码
程序员文章站
2022-06-25 11:08:01
1.package.json中
"dependencies": {
...
"vertx3-eventbus-client": "3.5.2",...
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.创建一个eventbus.service.ts用来通信
导入eventbus:
import { eventbus } from 'vertx3-eventbus-client';
声明eventbus:
declare var eventbus: any;
4.创建eventbus实例,监听接口以及发送消息
//创建实例 var eb = new eventbus('http://localhost:8080/eventbus'); eb.onopen = function() { //注册监听器用来接受消息 eb.registerhandler('some-address', function(error, message) { console.log('received a message: ' + json.stringify(message)); }); //发送消息 eb.send('some-address', {name: 'tim', age: 587}); }
更多信息请参考这里
注:
对于需要发送消息来接受的消息,需要先监听,然后再发送消息。
对于一直推送的消息,不需要发送。
代码实例如下:
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中调用closeeventbus关闭eventbus。
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。