How to get notifications in user applications?

2019-08-21 17:16发布

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条回答
趁早两清
2楼-- · 2019-08-21 17:49

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

查看更多
登录 后发表回答