为什么这家工厂返回$$状态对象,而不是response.data? [英] Why is this factory returning a $$state object instead of response.data?

查看:133
本文介绍了为什么这家工厂返回$$状态对象,而不是response.data?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我在服务器对象的集合,我要填充的NG-重复加载页面时。

我有一个做了一个工厂,获取列表从资源的服务器上,像这样:

  app.factory('objectArray',['$ HTTP',函数($ HTTP){
    //这个函数返回一个$$状态对象
    //而不是response.data ...
    返回$ http.post('/ get_collection')
    。然后(功能(响应){
      的console.log(response.data);
      返回response.data;
    });
  }]);

我已经使用的用户界面 - 路由器,在该州宣布决心属性时,在此之前code的工作。不过这家工厂直接注射到我的控制器时,不但得不到response.data我得到一个$$状态对象。

我的控制器看起来是这样的:

  app.controller('的ApplicationController',['$范围,objectArray',函数($范围,objectArray){    $ scope.array = objectArray;
    的console.log($ scope.array);  }]);


解决方案

什么$ http服务回报(因而 objectArray 服务)被称为一个承诺。您可以通过注册一个回调函数将被调用的时,数据可访问实际数据,即,当到HTTP请求的响应从服务器回来:

  objectArray.then(功能(数据){
    $ scope.array =数据;
});

您可以直接访问数据使用时的决心是路由器,当解析函数返回一个承诺,等待承诺要解决的原因。只有到那时,它提取自许的数据,并将数据注入到控制器。

要更好地了解诺言,你可以阅读下面的文章(及其续集)。

So I have a collection of objects in the server I want to populate an ng-repeat when the page loads.

I had a made a factory which fetched the list from a resource on the server, like so:

  app.factory('objectArray', ['$http',function($http) {
    // This is returning a $$state object
    // instead of response.data...
    return $http.post('/get_collection')
    .then(function(response) {
      console.log(response.data);
      return response.data;
    });
  }]);

I've had this code work before when using ui-router and the resolve property in the state declaration. However when injecting this factory directly into my controller, instead of getting response.data I am getting a $$state object.

My controller looks like this:

  app.controller('applicationController', ['$scope','objectArray',function($scope,objectArray) {

    $scope.array = objectArray;
    console.log($scope.array);

  }]);

解决方案

What the $http service returns (and thus the objectArray service is) is called a promise. You can access the actual data by registering a callback function that will be called when the data is available, i.e. when the response to the http request comes back from the server:

objectArray.then(function(data) {
    $scope.array = data;
});

The reason you directly have access to the data when using resolve is that the router, when the resolve function returns a promise, waits for the promise to be resolved. And only then, it extracts the data from the promise and injects the data into the controller.

To better understand promises, you could read the following article (and its sequel).

这篇关于为什么这家工厂返回$$状态对象,而不是response.data?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆