AngularJS http请求从不执行

AngularJS http request is never executed

本文关键字:执行 请求 http AngularJS      更新时间:2023-09-26

我在这里有一个最小的复数。

发生了什么:

  1. 成功发出初始$http请求
  2. 单击事件绑定到指令中的按钮
  3. 单击该按钮可启动所需的功能
  4. 该功能中的$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解析。

app.directive 'makeRequest', ($compile) ->
  scope:
    act: '&'
  link: (scope, element, attrs) ->
    element.bind 'click', (e) -> scope.act(); scope.$apply();