![](/img/trans.png)
[英]AngularJS unit test with $http request never fires .then() callbacks
[英]AngularJS http request is never executed
我在這里有一個最小的插件。
這是發生了什么:
$http
請求成功完成 $http
請求(與步驟1中的請求相同)不會觸發 因為代碼很短,我也會在這里發布。
<!DOCTYPE html>
<html ng-app="plunker">
<head>
<title>AngularJS Plunker</title>
<!-- angular source -->
<script src="app.js"></script>
</head>
<body ng-controller="MainCtrl">
<p>Click this button and an http request should log to the console</p>
<button make-request act='flip()'>Get Gaius</button>
</body>
</html>
app = angular.module('plunker', [])
app.controller 'MainCtrl', ($scope, $http) ->
# this function is just here to show that no errors are thrown
err = (err) -> console.log 'err', err
# this successfully gets
$http.get('gaius.json')
.then ((res) -> console.log 'init data', res.data), err
$scope.flip = ->
# although this function is called,
console.log 'called to act'
# http does not get. No request is made.
$http.get('gaius.json')
.then ((res) -> console.log 'flip data', res.data), err
app.directive 'makeRequest', ($compile) ->
scope:
act: '&'
link: (scope, element, attrs) ->
element.bind 'click', (e) -> scope.act()
{
"name": "gaius baltar"
}
知道為什么這個請求不執行?
您必須通過在作用域上調用$ apply()來傳播promise promise。
app.directive 'makeRequest', ($compile) ->
scope:
act: '&'
link: (scope, element, attrs) ->
element.bind 'click', (e) -> scope.act(); scope.$apply();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.