Javascript Angular http 返回 $$state 对象

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/28146491/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 01:16:45  来源:igfitidea点击:

Angular http returns $$state object

javascriptangularjsangular-services

提问by wdphd

I have the following factory defined:

我定义了以下工厂:

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

And my controller:

还有我的控制器:

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

Here's the console.log:

这是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?

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

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.

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

回答by Benjamin Gruenbaum

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

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

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 resolveoption in the route. Also see this related question.

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

回答by shaunhusain

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

      return factObj;
    };
  }
]);

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

In your view

在你看来

<div ng-controller="TestCtrl as test">{{test.userService.user}}</div>

Edits based on comments, true this would not work with the controller or view as you probably had them, but this pattern works well and removes the need to have .then in every controller that may re-use the data.

根据评论进行编辑,确实这不适用于您可能拥有的控制器或视图,但这种模式运行良好,并且无需在每个可能重用数据的控制器中使用 .then。

Typically storing your model in the factory or service that deals with fetching the data makes for an easier path to getting the data into every view where you need it. Down side here is you'd be fetching the user when this factory is referenced instead of explicitly firing the getUser function from the controller. If you want to get around that you can store the promise from the first time it's requested in the getUser function and just return that promise for all subsequent calls if it's already set, this way you can call getUser multiple times without repeating the API request.

通常,将您的模型存储在处理获取数据的工厂或服务中,可以更轻松地将数据放入您需要的每个视图中。不利的一面是,您将在引用此工厂时获取用户,而不是从控制器显式触发 getUser 函数。如果你想解决这个问题,你可以从第一次在 getUser 函数中请求它时存储承诺,如果它已经设置,则只需为所有后续调用返回该承诺,这样你就可以多次调用 getUser 而不重复 API 请求。

回答by sireken

I have here a similar scenario.. I hope it helps somebody...

我在这里有一个类似的场景..我希望它可以帮助某人......

my factory ..

我的工厂..

 angular.module('programList.services',[])
    .factory('PROGRAMS', function($http) {
     return {
       getprogramList: function() {
       return $http.get('/api/programs/list').then(function(result) {
       return result.data[0];
       });
      }
     };
    });

This is my controller ..

这是我的控制器..

 angular.module('programList.services'])
 .controller('tviProgramsController',
    function($scope,$state,$stateParams,PROGRAMS){
        //this is the call to access the list as answered by Benjamin Above using then on success 
        PROGRAMS.getprogramList().then(function(list){
                  $scope.programlist = list;
              });
  });

;

This is on the router on server side...

这是在服务器端的路由器上...

  var express     = require('express'),
     programscontroller = require(path + 'programservercontroller'),
     router         = new express.Router();
     router.get('/api/programs/list', programscontroller.programlist);

This is the module for mysql call

这是mysql调用的模块

var con   = require('../../database/dbcon'),
mysql = require('mysql');

module.exports.programlist = function(req, res){
 var data = req.params.data;
 var sql = "CALL `sp_programlist`";
  con.query(sql, function(err, result) {
      if(err){
          throw err;
      } else {
          res.send(JSON.stringify(result));
      }
     });
};