Angular using Server Sent Events in a factory

前端 未结 2 1848
佛祖请我去吃肉
佛祖请我去吃肉 2021-01-28 17:36

I am trying to setup message notifications in an Angular/Rails app.

When the user logs in, I want to open a SSE connection which will subscribe to a Redis stream and pu

2条回答
  •  情深已故
    2021-01-28 18:10

    The problem was that I was putting the function that creates an EventSource in my get attribute, instead of putting the actual EventSource object. A few changes makes it work:

    .factory('StreamHandler', function(CookieHandler, MessageStream){
      var StreamHandler = {
    
        set: function(){
          var user
          user = CookieHandler.get();
          var source = new EventSource('/api/v1/messages/count?id='+user.id)
          MessageStream.get = source
        },
    
        get: function(){
          var source = MessageStream.get
          source.onmessage = function(event) {
            console.log(event)
          }
          source.onerror = function(error) {
            source.close()
          }
        },
    
        kill: function(){
          var source = MessageStream.get
          source.close();
    
        }
      }
    
      return StreamHandler
    })
    

提交回复
热议问题