简体   繁体   English

AngularJS工厂返回State对象而不是promise中的JSON数据

[英]AngularJS factory returning State object instead of JSON data from promise

I have made two factory and calling first from second one, consuming second one factory in controller but instead of getting data as JSON, I'm getting data as $$State. 我已经制作了两个工厂并从第二个工厂首先调用,在控制器中占用第二个工厂,但不是将数据作为JSON获取,而是将数据作为$$状态获取。 I'm new to angularJS tried many ways but not able to solve, please help. 我是angularJS的新手尝试了许多方法,但无法解决,请帮忙。

 app.factory('userDetails', ['APIService', '$q', function (APIService, $q) {
    getDetails: function () {
        var deferred = $q.defer();
        var getFunc = function () {
            APIService.doGetCall('Masters/employee/username/tarun')
                .then(
                function (data)
                { 
                    deferred.resolve(data);
                },
                function (data, status, headers, config)
                { 
                    deferred.reject('There was an error creating object'); })
                    return deferred.promise;
                 }
        var a = getFunc();
        return a;

    }
}

 vm.user = userDetails.getDetails();
console.log("user",vm.user);

response is as per below snippet 响应如下面的片段

Response 响应

userDetails.getDetails() returns a promise, Hence you need to use .then(onsuccess, onRejected) userDetails.getDetails()返回一个promise,因此你需要使用.then(onsuccess, onRejected)

userDetails.getDetails().then(function(data){
   vm.user = data;
   console.log("user",vm.user);
});

You should be using .then function to get response there. 你应该使用.then函数来获得响应。 Rather I'd say you don't need to create extra promise, its an anti-pattern . 相反,我会说你不需要创造额外的承诺,它是一种anti-pattern Where you could utilize the promise return by doGetCall method directly. 您可以直接使用doGetCall方法返回承诺。

app.factory('userDetails', ['APIService', '$q', function(APIService, $q) {
  getDetails: function() {
    var getFunc = function() {
      return APIService.doGetCall('Masters/employee/username/tarun');
    }
    var a = getFunc();
    return a;
  }
}]);

vm.user = userDetails.getDetails().then(function(response){
    console.log(response.data);
    vm.user = response.data;
    console.log("user", vm.user);
}, function(error){
    console.log(error)
}).catch(exceptionHandler);

You've got the 你有

return deferred.promise;

line inside the APIService.doGetCall function. APIService.doGetCall函数内的一行。 It should be outside of it. 它应该在它之外。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM