2014-11-23 60 views
1

我有一份依賴客戶參數的出版物。因此,在從客戶端訂閱時,我需要將此參數發送到服務器。 我正在使用角流星包,並發現了$subscribe包裝。 用法如下:$subscribe.subscribe(name, publisherArguments) 我想通過動態$範圍值的訂閱,但它似乎並不工作。例如,以下示例從不提醒「您訂閱!」Meteor和AngularJS被動訂閱

$subscribe.subscribe('aPublication',$scope.parameter).then(function(){ 
     alert("You subscribed !"); 
    }); 

假設服務器端看起來像這樣

Meteor.publish("aPublication", function (parameter) { 
    ACollection.find({'aProperty':'parameter'}) }); 

我應該怎麼做,使$scope.parameter以同樣的方式,如果我用Session.get('parameter')

回答

1

@Flavien Volken,這是一個非常好的解決方案,但在我們的新版本0.6.0你也可以解決一點更類似於流星做到這一點的方式使用scope.getReactively - http://angularjs.meteor.com/api/getReactively

所以在你的解決方案中:

$meteorUtils.autorun($scope, function() {  
    $meteorSubscribe.subscribe('aPublication', 
           $scope.getReactively('parameter')) 
          .then(function(){ 
            alert("You subscribed !"); 
     }); 
}); 
1

這裏是我的工廠,它確實有這樣的形狀,我將它綁定到一個

angular.module('myApp.controllers').factory('items', function() { 

     var listOfItems = [ 
      {name: "one"}, 
      {name: "two"}, 
      {name: "three"}]; 

     var currentItem = listOfItems[1]; 

     return { 
      'list': listOfItems, 
      'current': currentItem 
     }; 
    }); 

這裏,然後我的控制,我基本上是看改變爲cities.current值那麼火了currentItemChanged函數將使用正確的參數進行訂閱。

angular.module('myApp.controllers').controller("MyCtrl", ['$scope', 'items', '$subscribe', 
    function ($scope, items, $subscribe) { 

      $scope.$watch(function() { 
       return cities.current; 
      }, function (currentItem) 
      { 
       currentItemChanged(currentItem.name); 
      }, true); 

      function currentCityChanged(itemName) 
      { 
       // resubscribe to the right set of 
       $subscribe.subscribe('anItemsSubscription', itemName).then(function() 
       { 

       }); 
      }