Data is not getting updated in the view after promise is resolved

爱⌒轻易说出口 提交于 2019-12-31 03:18:08

问题


I am using my Rails app as an API backend. So I have a single page angular app which will make multiple api calls and start displaying as each data gets returned. I don't want to wait for all the results from the API call and then load the data, so I started learning deferred and promise.

I have an angular service called api where I will have $http calls to all my api. I have hardcoded the data that returns from each one of the api calls for testing purposes.

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
]

I have created an edge service to call methods from my api service. I have used $timeout to simulate the async api calls.

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

In my EdgeController I call the service and attach the value to $scope.data

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

debugger.$inject = ["$scope"]

This is my slim template

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}}

The output is not getting binded'

Also is this the best way to implement if I have to make multiple api calls and update the view as each one returns?


回答1:


$scope.data = EdgeService.tickets()

Should be

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

AngularJS does not automatically unwrap promises in newer versions. This would work in older versions of Angular.

To do multiple API calls dependant of one another you can do

callA
.then(callB)
.then(callC)

Yo can do multiple in parallell using $q.all

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


来源:https://stackoverflow.com/questions/20481327/data-is-not-getting-updated-in-the-view-after-promise-is-resolved

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!