2013-12-09 100 views
2

我正在使用我的Rails应用程序作为API后端。所以我有一个单页的角度应用程序,它会进行多个api调用,并在每个数据返回时开始显示。我不想等待API调用的所有结果,然后加载数据,因此我开始学习延期和承诺。解决承诺后数据未在视图中更新

我有一个角度服务叫做api在那里我将$ http调用所有我的api。为了进行测试,我对每个api调用返回的数据进行了硬编码。

debugger.factory "api", ["$resource", "$q", ($resource, $q) -> 
    apiCall1 = [ 
    key1: "v1" 
    key2: "v2" 
    key3: "v3" 
    ] 

    apiCall2 = 
    . 
    . 
    . 
    apiCall7 = 

    factory = getIsDynamicApp: -> 
    deferred = $q.defer() 
    deferred.resolve apiCall1 
    deferred.promise 

    factory 
] 

我已经创建了一个边缘服务来从我的api服务调用方法。我用$超时来模拟异步API调用。

debugger.factory "EdgeService", ($resource, api, $q, $timeout, $http) -> 

    fetchIsDynamic = -> 
    api.getIsDynamicApp() 

    tickets: -> 
    deferred = $q.defer() 
    fetchIsDynamic().then (data) -> 
     $timeout (-> 
     deferred.resolve data 
     console.log data #<- this works, I can see the data 
    ), 3000 
    deferred.promise 

在我EdgeController我所说的服务和附加价值$ scope.data

debugger.controller "EdgeController", ($scope, EdgeService) -> 
    $scope.load = -> 
    $scope.data = EdgeService.tickets() 

debugger.$inject = ["$scope"] 

这是我的苗条模板

doctype html 
html(ng-app="debugger" class="ng-scope") 
    head 
    title Ads Debugger 
    = stylesheet_link_tag "application/debugger" 
    = javascript_include_tag "debugger" 

    body 
    #content(ng-controller="EdgeController") 
     .search_form 
     form class="serch_form" 
      input type="text" name="search_box" id="search_box" 
      input type="submit" value="Search" ng-click="load()" 

     div 
     pre message {{data}} 

输出没有得到绑定”

enter image description here

也是这是实现的最佳方式,如果我必须进行多个api调用并更新每个人返回的视图?

+0

我建议在JS提供的例子,和/或一个plnkr或小提琴:) –

回答

4
$scope.data = EdgeService.tickets() 

应该

EdgeService.tickets().then (data) -> 
$scope.data = data 

AngularJS不会自动解开承诺in newer versions。这可以在老版本的Angular中使用。

做多的API调用依赖彼此的你可以做

callA 
.then(callB) 
.then(callC) 

哟可以用做parallell多个$ q.all

$q.all([callA, callB, callC]).then(....) 
+0

非常感谢!此外,我正在制定数据数组并在每次调用后将值推入数组。这是最好的方法吗? –

+0

我的api调用不依赖于另一个。 $ q.all将等待所有api调用返回promise,然后执行一些操作。但我想要更新我的观点,因为我得到的结果。我的一个API调用需要1分钟,所以我无法等待这么久显示其他值。 –