2017-01-09 118 views
0

我完全停留在嘗試進行方法的同步調用。我試圖從服務器端獲取客戶端列表(簡化版本,原本是另一個API的調用),並在網頁上打印此列表。來自客戶端(角度)端的流星方法的同步呼叫

客戶端代碼(角1):

import template from './clientsList.html'; 
import {Meteor} from 'meteor/meteor'; 

class ClientsList { 
    constructor() { 
     console.log('First'); 
     Meteor.call('getClients', function (error, response) { 
      if (error) { 
       // If our API returned an error, we'd see it in the console. 
       console.log(error); 
      } else { 
       console.log(response); 
       this.clients = response; 
      } 
     }); 
     console.log('Second'); 
    } 
} 

const name = 'clientsList'; 

export default angular.module(name, [ 
    angularMeteor 
]).component(name, { 
    template, 
    controllerAs: name, 
    controller: ClientsList 
}) 
} 

服務器端代碼(流星):

import {Meteor} from 'meteor/meteor'; 
    var Future = Npm.require('fibers/future'); 

    Meteor.methods({ 
      // Synchronous method 
     'getClients': function() { 
      // Create our future instance. 
      var future = new Future(); 
var clients = {[Name: 'Peter']};  
      future.return(clients); 
      // preventinvg method from completing until the future receives a value 
      return future.wait(); 
     } 
    }); 

模板:

<ul> 
     <li ng-repeat="client in clientsList.clients"> 
       {{client.Name}} 

     </li> 
    </ul> 

看來,我使用的未來,使服務器端代碼同步工作不起作用。這是我得到我的控制檯:

First 
Second 
Array[1] 

期待:

First 
Array[1] 
Second 

我會很感激的任何幫助。

+0

您在代碼的同步部分(嚴格在方法內部)有未來。如果您的方法本身正在進行異步調用,但它不是,這會很有用。你需要客戶的承諾。此外,您的方法('getClients')的名稱意味着您可以使用pub-sub時使用方法來獲取數據。 –

+1

@MichelFloyd,OP建議原始的服務器代碼調用一個API,因此它可能是異步的。 @OP,請注意,在進行API調用時,您可以在服務器上以同步方式使用[http包](https://docs.meteor.com/api/http.html)。即使您正在使用第三方API庫,也可以使用['wrapasync'](https://docs.meteor.com/api/core.html#Meteor-wrapAsync)對其進行封裝,但使用「Future」if這是你喜歡的。 – MasterAM

+0

正確,但看看他在客戶端進行異步調用的代碼,但期望'First,Array [1],Second'不管他在服務器上做什麼都不會發生,因爲Meteor.call()是異步的。 –

回答

2

您的服務器端代碼(如果它工作正常)只是在未來解決問題時解決呼叫問題。

這使得客戶端回調被調用時,服務器有實際的數據,但它仍然不會同步(沒有辦法使其在客戶端上同步)。

您可以嘗試使用promises,async/await(ES7)或observables(RxJS)來簡化您的代碼,但它始終是幕後異步。

+0

謝謝,現在有道理!所以當我設置this.clients = response;在客戶端,我怎樣才能讓它顯示在模板上?因爲我認爲這是因爲我的代碼是異步的,但是,根據你的說法,它在客戶端一直是異步的。所以我的客戶不會顯示在模板上。如何解決這個問題? – grehemmm

0

從客戶端到服務器的方法調用不能同步。你應該閱讀這Meteor.call

0

你看到的是正確的。從客戶端到服務器的調用是異步的,對此你無能爲力。

在你的模板中,你基本上做了3件事:記錄'第一',進行異步調用和記錄'秒'。

稍後,您的異步調用返回並輸入流星調用的回調。那就是當你做第三個console.log()。

我意識到你正在同步處理服務器調用本身,但這與客戶端和服務器之間的異步行爲無關。

+0

謝謝!有什麼辦法讓模板「等待」Angular中的異步方法獲得響應並將其分配給this.clients值?因爲現在看起來,它立即啓動模板而不等到構造函數完全完成併爲this.clients變量賦值。 – grehemmm