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

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

问题描述

我定义了以下工厂:

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 承诺。为了打开它,你必须链接到它然后打开它:

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);
        });
}]);

如果您正在使用路由,您可能还需要查看解析路线中的选项。另请参阅此相关问题

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返回$$状态对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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