角$ HTTP返回的数据,但并不适用于范围 [英] Angular $http returns data but doesn't apply to scope

查看:97
本文介绍了角$ HTTP返回的数据,但并不适用于范围的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在角度,我有这样的工厂

In angular, I have this factory

.factory('Users', function($http) {
  var users = [];

  return {
    getUsers: function() {
      return $http.get("data.json")
        .then(function(response) {
          users = response.data;
          return users;        
        });
    },
    getUser: function(id) {
      for (i = 0; i < users.length; i++) {
        if (users[i].id == id) {
          return users[i];
        }
      }
      return null;
    }
  }
})

然后加载在我的控制器,数据

And then load that data in my controller

.controller('SessionsCtrl', function($scope, Users) {
  $scope.users = Users.getUsers();
})

如果我CONSOLE.LOG从http请求的响应时,我得到的数据,但由于某些原因,该范围的数据将不更新

If I console.log the response from the http request, I am getting the data, but for some reason, the scope data won't update.

我见过的例子,其中控制器看起来像这样

I've seen examples where the controller would look like this

Users.getUsers().then(function(data) {
    $scope.users = data;
});

但是从我的理解,我不应该需要,因为 $ HTTP 已返回一个承诺。我缺少的东西吗?我是否需要在所有涉及 $ Q

but from my understanding, I shouldn't need to since $http is already returning a promise. Am I missing something? Do I need to involve $q at all?

推荐答案

这将工作:

 getUsers: function() {
      return $http.get("data.json");
    },

Users.getUsers().then(function(data) {
    $scope.users = data.data;
});

你写不过是行不通的,仅仅是因为你不能直接从一个操作将完成以后,如 $ HTTP 调用返回的结果。
与此问题:

What you wrote however will not work, simply because you can't directly return a result from an operation that will complete later such as a $http call. The problem with this:

 getUsers: function() {
      return $http.get("data.json")
        .then(function(response) {
          users = response.data;
          return users;        
        });
    },

是由当时的回报用户; 行执行的Ajax调用仍在进行中,目前尚无回来了,所以你会得到什么用户。对于你在找什么做的我会去用回调:

Is that by the time the return users; line executes the ajax call is still in progress and nothing has been returned yet, so you will get nothing for users. For what you're looking to do I would go about using a callback:

 getUsers: function(callback) {
        $http.get("data.json")
         .then(function(response) {
          users = response.data;
          callback(users);        
        });
    },

用法:

Users.getUsers(function(data) {
    $scope.users = data;
});

这篇关于角$ HTTP返回的数据,但并不适用于范围的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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