2017-02-14 9 views
0

在我的流星項目中,我試圖獲得一個流星對象並在html中進行迭代。無法接收html內的流星對象

我的HTML代碼如下:

<ul> 
    {{#each userTerritory myObject}} 
    <li class="">{{myObject.name}}</li> 
    {{/each}} 
    </ul> 

在client.js創建一個輔助類和我做的方法調用如下從蒙戈DB

Template.dash_board_content1.helpers({ 

     'userTerritory': function(){ 

     Meteor.call('userTerritoryList',function(error,result){ 
      console.log(result); 
      if(!error){ 

      return result; 

        }else{ 
      alert("error : " + error); 
      } 

     }); 
     } 
    }); 

方法檢索對象在server.js中如下所示:

in server.js 

'userTerritoryList': function(){ 
    console.log("testing"); 
    return Country.find().fetch();; 
} 
+0

爲什麼要在這裏調用Meteor方法而不是發佈/訂閱? – zim

+0

@zim使用方法被認爲是更好的安全方法。曾多次建議使用方法並實施對真實性,角色等的檢查。 – Jankapunkt

+0

我想你正在考慮Meteor方法vs客戶端寫入。 pub/sub是安全的,imho比方法調用更適合您的問題。 – zim

回答

0

流星方法在默認情況下不適用於Blaze的助手,讓他們一起工作,你可以使用這個包:meteor-reactive-method

Template.dash_board_content1.helpers({ 
    userTerritory: function(){ 
    return ReactiveMethod.call('userTerritoryList'); 
    } 
}); 
0

編輯:作爲@zim指出的那樣,你可能會喜歡使用流星的發佈和訂閱功能。這將是您描述的問題的最佳解決方案。

閱讀資料上:https://guide.meteor.com/data-loading.html

如果仍然依賴於使用你的服務器端調用,您可以使用該方法反應包,@Khang指出。如果你想對自己的結果數值更細粒度的訪問,你應該使用一個反應字典:

import {Template} from 'meteor/templating'; 
import {ReactiveDict} from 'meteor/reactive-dict'; 

// create a new reactive dictionary to store reactive variables 
// let's call it state 
Template.dash_board_content1.onCreated(function onCreated(){ 

    //this refers to the Template.instance() here 
    this.state = new ReactiveDict(); 

    //initial value of userTerritoryList is null 
    //it will return nothing until it has been changed 
    this.state.set('userTerritoryList', null); 
    //you can even set an errors variable 
    this.state.set('errors', []); 
}); 

然後你就可以通過Template.instance訪問活性字典():

Template.dash_board_content1.helpers({ 

    'userTerritory': function(){ 
     const territoryList = Template.instance().state.get('userTerritoryList'); 

     if (territoryList) return territoryList; 

     Meteor.call('userTerritoryList', function(error,result){ 
      if(!error){ 
       Template.instance().state.set('userTerritoryList', result); 
      } else { 
       const errs = Template.instance().state.get('errors'); 
       errs.push(error); 
       //update errors 
       Template.instance().state.set('errors', errs); 
      } 
     }); 
    }, 

    'getErrors' : function() { 
     //use in your template to display multiple err messages 
     return Template.instance().state.get('errors'); 
    }, 
}); 

的useTerritory只有在尚未設置的情況下,助手纔會使用Meteor.call。不過,您可以輕鬆更改方法,以便始終調用方法。

請注意,您可以從而實現更細化的錯誤處理。

+0

imho助手不應該是異步的。最好將方法調用放在onCreated()的autorun()中,並讓幫助程序返回無功變量的內容。 – zim

+0

你也可以這樣做。我更喜歡這種方法來防止自動運行過大。當所有無功變量相關代碼就位時,它使我更容易進行調試。 – Jankapunkt