我是第一次使用 Angular 1.2.18。我将它与 Rails 3.2 和 coffeescript 一起使用。我正在尝试在服务中使用 promise 来获取一些数据,然后我将使用这些数据来填充模板。我的代码如下所示:
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
)
}
])
当我尝试这样做时,我得到“undefined is not a function”并且没有有用的堆栈跟踪。我不确定哪个部分未定义。我考虑过在 config() 中执行此操作,但直到运行时我才知道 $http.get(url) 中的 url 是什么。任何有关以“Angular 方式”执行此操作的帮助或建议,我们将不胜感激。
最佳答案
fetchService.getData
返回一个 $q
promise ,而不是一个 $http
promise ,所以你不能调用 `.success
fetchService.getData($scope.url).success( (data) ->
这里需要改成
fetchService.getData($scope.url).then( (data) ->
关于javascript - Angular promise 在服务中的响应问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24814209/