How to get notifications in user applications?

蹲街弑〆低调 提交于 2019-12-13 20:23:34

问题


In blockchain I have emitted an event which is linked with a particular transaction. I have also subscribed the event in my transaction API. But what do I do after I subscribe the event in the API? I do not know how to generate notifications in my front-end or user application using this subscribed event which was emitted by the blockchain end. Kindly help.


回答1:


You can use WebSocket to get events occurs on URL by using WebSocket in JS.

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();

Above code will continuous monitor given URL & if any event occurs, then it will call the function doSocketMessage().



来源:https://stackoverflow.com/questions/52987236/how-to-get-notifications-in-user-applications

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!