【问题标题】:How to get notifications in user applications?如何在用户应用程序中获取通知?
【发布时间】:2018-10-25 10:36:59
【问题描述】:
在区块链中,我发出了一个与特定交易相关联的事件。我还在我的事务 API 中订阅了该事件。但是我在 API 中订阅了事件后该怎么办?我不知道如何使用区块链端发出的这个订阅事件在我的前端或用户应用程序中生成通知。请帮忙。
【问题讨论】:
标签:
hyperledger-fabric
hyperledger
blockchain
hyperledger-composer
ibm-blockchain
【解决方案1】:
您可以使用WebSocket在JS中使用WebSocket获取URL上发生的事件。
class Events {
constructor() {
// Listen for events
this.socket = new WebSocket(Events.URL_TRANSACTION);
this.socket.addEventListener('open', evt => this.doSocketOpen(evt));
this.socket.addEventListener('close', evt => this.doSocketClose(evt));
this.socket.addEventListener('message', evt => this.doSocketMessage(evt));
// Load initial data
this.xhr = new XMLHttpRequest();
this.xhr.addEventListener('load', evt => this.doInitialLoad1(evt));
this.xhr.open('GET', Events.URL_ASSET1, true);
this.xhr.send(null);
}
// Initial data loaded
doInitialLoad1(evt) {
var data = JSON.parse(this.xhr.responseText);
console.log(data);
}
// FYI
doSocketClose(evt) {
console.log('Close.');
}
// Transaction has taken place
doSocketMessage(evt) {
let data = JSON.parse(evt.data); // getting event data here
console.log(data);
}
// FYI
doSocketOpen(evt) {
console.log('Open.');
}
}
Events.newData = '';
Events.URL_ASSET1 = 'http://localhost:3000/api/org.demo.SampleAsset';
Events.URL_TRANSACTION = 'ws://localhost:3000';
let app = new Events();
上面的代码会持续监控给定的URL,如果有任何事件发生,就会调用函数doSocketMessage()。