wdp*_*phd 16 javascript angularjs angular-services
我有以下工厂定义:
angular.module("account").factory("users",["$http",
function(a){
return {
getUser: function(){
return a.get("/user/me").then(function(r){
return r.data;
});
}
};
}
]);
Run Code Online (Sandbox Code Playgroud)
而我的控制器:
angular.module("test.controllers",["account"])
.controller("TestCtrl",["$scope","users",
function(a,u){
a.user = u.getUser();
console.log(a.user);
}]);
Run Code Online (Sandbox Code Playgroud)
这是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
Run Code Online (Sandbox Code Playgroud)
上面的代码返回一个状态对象而不是用户对象.但是从日志中,状态对象具有值内的用户对象.我如何获得用户对象?或者我这样做完全错了吗?
我知道另一种方法是返回$ http.get并在控制器中调用then()方法.但我会经常使用用户对象,如果我在控制器中调用then()方法,它几乎与在控制器而不是工厂中使用$ http.get相同.
Ben*_*aum 25
通常是JavaScript I/O,在这种情况下包括异步.您的getUser通话会返回$ q 承诺.为了打开它,你必须链接到它,然后打开它:
angular.module("test.controllers",["account"])
.controller("TestCtrl",["$scope","users",
function(a,u){
u.getUser().then(function(user){
a.user = user;
console.log(a.user);
});
}]);
Run Code Online (Sandbox Code Playgroud)
如果您正在使用路由,您可能还需要查看路由中的resolve选项.另请参阅此相关问题.
| 归档时间: |
|
| 查看次数: |
33186 次 |
| 最近记录: |