承诺解决后,视图中的数据不会更新

时间:2013-12-09 21:36:55

标签: angularjs coffeescript promise slim

我正在使用我的Rails应用程序作为API后端。所以我有一个单页角应用程序,它将进行多个api调用并在每个数据返回时开始显示。我不想等待API调用的所有结果然后加载数据,所以我开始学习延迟和承诺。

我有一个名为 api 的角度服务,我将对所有api进行$ http调用。为了测试目的,我已经硬编码了从每个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服务中调用方法。我使用$ timeout来模拟异步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调用并在每次返回时更新视图,这也是最好的实现方式吗?

1 个答案:

答案 0 :(得分:4)

$scope.data = EdgeService.tickets()

应该是

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

AngularJS不会自动解包承诺in newer versions。这适用于较早版本的Angular。

要执行彼此依赖的多个API调用,您可以执行

callA
.then(callB)
.then(callC)

Yo可以使用$ q.all

并行执行多个操作
$q.all([callA, callB, callC]).then( .... )