Angular http 返回 $$state 对象 [英] Angular http returns $$state object

查看:27
本文介绍了Angular http 返回 $$state 对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我定义了以下工厂:

angular.module("account").factory("users",["$http",
    function(a){
      return {
         getUser: function(){
            return a.get("/user/me").then(function(r){
                return r.data;
            });
        }
    };
  }
]);

还有我的控制器:

angular.module("test.controllers",["account"])
.controller("TestCtrl",["$scope","users",
    function(a,u){
        a.user = u.getUser();
        console.log(a.user);
}]);

这是console.log:

Here's the console.log:

 d {$$state: Object, then: function, catch: function, finally: function} $$state: Object status: 1 value: Object user: Object__v: 0 _id: "54c1fg29f36e117332000005" temp: "1ce3793175e0b2548fb9918385c2de09"  __proto__: Object __proto__: Object __proto__: Object __proto__: Object

上面的代码返回的是状态对象而不是用户对象.但是从日志来看,状态对象具有值内的用户对象.我如何获取用户对象?还是我这样做完全错误?

The above code is returning a state object instead of the user object. But from the log, the state object has the user object within value. How do i get the user object? Or am i doing this completely wrong?

我知道另一种方法是返回 $http.get 并在控制器中调用 then() 方法.但是我会经常使用用户对象,如果我在控制器中调用 then() 方法,它几乎与在控制​​器中使用 $http.get 而不是工厂相同.

I know the other way is to return the $http.get and call the then() method within controller. But I'll be using the user object frequently and if i'm calling the then() method in controller, its almost same as using the $http.get in controller instead of the factory.

推荐答案

JavaScript I/O 通常是,在这种情况下包括异步.您的 getUser 调用返回 $q promise.为了解开它,你必须链接到它然后像这样解开它:

JavaScript I/O is usually, including in this case asynchronous. Your getUser call returns a $q promise. In order to unwrap it you have to chain to it and then unwrap it as such:

angular.module("test.controllers",["account"])
.controller("TestCtrl",["$scope","users",
    function(a,u){
        u.getUser().then(function(user){
            a.user = user;
            console.log(a.user);
        });
}]);

如果您使用路由,您可能还想查看路由中的 resolve 选项.另请参阅此相关问题.

If you're using routing you might also want to look into the resolve option in the route. Also see this related question.

这篇关于Angular http 返回 $$state 对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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