简体   繁体   中英

Problems with angular promises' responses in services

I'm working with angular 1.2.18 for the first time. I am using it with rails 3.2 and coffeescript. I am trying to use a promise in a service to fetch some data that I will then use to populate a template. My code looks like this:

angular.module('myApp')
.service('fetchService', ['$http', '$q', ($http, $q) ->
 theService = {}
  theService.myData = null

  theService.getData = (url) ->
    q = $q.defer()

    if this.myData
      q.resolve(this.myData)
      return q.promise

    self = this
    $http.get(url).then(
      (successResonse)->
        self.myData = successResponse
        q.resolve(successResponse)
      ,(errorResponse)->
        self.myData = errorResponse
        q.reject(errorResponse)
    )

    return q.promise
  return theService
])

.directive('myDirective', ["fetchService", fetchService)->
  return {
    restrict: "A"
    templateUrl: "/my_template_url"
    scope:
      url: '@shopUrl'
      offset: '@'
        controller: ($scope, fetchService)->
      fetchService.getData($scope.url).success( (data) ->
        $scope.content = data.content
      )
  }
])

When I try to do this, I get "undefined is not a function" and no useful stack trace. I am not sure which part is undefined. I have thought about doing this in a config(), but I don't know what the url in $http.get(url) is until runtime. Any help or advice on doing this the "angular way" would be appreciated.

fetchService.getData is returning a $q promise, not an $http promise, so you can't call `.success on it.

fetchService.getData($scope.url).success( (data) ->

This needs to be changed to

fetchService.getData($scope.url).then( (data) ->

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM