编程语言
首页 > 编程语言> > javascript – AngularJS:$routeProvider解析$http时返回响应obj而不是我的obj

javascript – AngularJS:$routeProvider解析$http时返回响应obj而不是我的obj

作者:互联网

我正在尝试解决几个ajax调用,以便我的控制器需要的数据在它(以及它提供的指令)执行之前可用.但是,执行的顺序是有效的,而不是返回我创建的对象,注入我的控制器的结果是$http的响应对象:

{
  config: { … },
  data: { … },
  headers: { … },
  status: 200
}

我的代码基本上看起来像:

app.config([
  '$routeProvider', function($routeProvider)
  {
    $routeProvider
      .when('/path', {
        …,
        "resolve": {
          "data": [
            '$http',
            function($http)
            {
              return $http
                .get('/api/data')
                .success(function(data,status) { return data.rows[0]; })
                .error(function(data,status)   { return false; });
            }
          ]
        }
      });
  }
]);

我愚蠢吗? $http的成功的返回值实际上不应该是$http返回的值吗?

我也试过了

…
"resolve": {
  "data": [
    '$http',
    function($http)
    {
      var response;
      $http
        .get('/api/data')
        .success(function(data,status) { response = data.rows[0]; })
        .error(function(data,status)   { response = false; });
      return response;
    }
  ]
}

但是注入我的控制器的数据对象是未定义的(我猜是因为$http是异步的并且解析没有被$http阻止 – 所以它在$http准备好之前就返回了).

附: $http的同步性应该在其选项对象中定义!!

app.config([
  '$routeProvider', function($routeProvider)
  {
    $routeProvider
      .when('/path', {
        …,
        "resolve": {
          "data": [
            '$http',
            function($http)
            {
              return $http
                .get('/api/data')
                .then(
                  function success(response) { return response.data.rows[0]; },
                  function error(reason)     { return false; }
                );
            }
          ]
        }
      });
  }
]);

感谢Ajay beniwal’s pointerMark Rajcok’s pointer.

附:然后()记录于$q‘s page.

解决方法:

$http @returns {HttpPromise} Returns a {@link ng.$q promise} object
with the
standard then method and two http specific methods: success and error. The then
method takes two arguments a success and an error callback which will be called with a
response object. The success and error methods take a single argument – a function that
will be called when the request succeeds or fails respectively. The arguments passed into
these functions are destructured representation of the response object passed into the
then method. The response object has these properties:

标签:javascript,angularjs,resolver,route-provider
来源: https://codeday.me/bug/20190703/1368926.html