将范围对象绑定到工厂对象

时间:2017-11-19 20:24:42

标签: angularjs data-binding

我正在连接工厂中的websocket feed,它为我提供了实时比特币价格数据。

我将service.prices定义为websocketFactory中的对象,并在控制器中设置wsvm.prices = websocketFactory.prices

wsvm.prices.btc属性未在视图中更新,但在控制台中正确记录。

代码:

工厂

app.factory('websocketFactory', ['$http', function($http) {
  var service = {}
  service.prices = {
    "btc": 0
  }
  service.gdax = function() {
    const socket = new WebSocket('wss://ws-feed.gdax.com')
    var message = {
      "type": "subscribe",
      "channels": [{
        "name": "ticker",
        "product_ids": [
          "BTC-USD"
        ]
      }, ]
    }

    socket.addEventListener('open', function(event) {
      socket.send(JSON.stringify(message));
    })

    // Listen for messages
    socket.addEventListener('message', function(event) {
      var dataObj = JSON.parse(event.data)
      if (dataObj.price) {
        console.log(dataObj.price) //logging real time data
        service.prices.btc = dataObj.price //this should be updating the view
      }
    });
  }

  return service
}])

控制器

app.controller('WebsocketController', WebsocketController)
WebsocketController.$inject = ['$scope', 'websocketFactory']

function WebsocketController($scope, websocketFactory) {

  var wsvm = this

  wsvm.prices = websocketFactory.prices
  
  websocketFactory.gdax()

}

视图

<div ng-controller="PortfolioController as vm">
  <div class="row">
    <div class="col-sm-6">
      <h2 style="text-align: center;">Account Balances</h2>
    </div>
    <div class="col-sm-6">
      <table class="table">
        <thead>
          <tr>
            <td>24h Change</td>
            <td>Total Val USD</td>
            <td>BTC Price</td>
          </tr>
        </thead>
        <tbody>
          <tr>
            <td ng-class="{change_loss: vm.totals.change_24h_usd < 0, change_win: vm.totals.change_24h_usd > 0}"><b>{{vm.totals.change_24h_usd | currency}}</b></td>
            <td><b>{{vm.totals.total_usd | currency}}</b></td>
            <td ng-controller="WebsocketController as wsvm">{{wsvm.prices.btc}}</td>
          </tr>
        </tbody>
      </table>
    </div>
  </div>

如何正确地将工厂绑定到控制器以获取实时数据?

1 个答案:

答案 0 :(得分:0)

更改套接字侦听器中的范围超出了角度上下文。每当发生这种情况时,需要通知角度来运行摘要以更新视图

尝试以下方法:

app.factory('websocketFactory', ['$http', '$rootScope', function($http, $rootScope) {
   ......

  socket.addEventListener('message', function(event) {
      var dataObj = JSON.parse(event.data)
      if (dataObj.price) {
        console.log(dataObj.price) //logging real time data

        $rootScope.$apply(function(){
            service.prices.btc = dataObj.price //this should be updating the view
        });
      }
    });
});

我还建议您寻找一个角度套接字模块,它将在内部为您完成所有这些工作