简体   繁体   English

AngularJS中的Promise错误

[英]Error in promises in AngularJS

I'm using a promise to get data from a json in my service and then passing it to my controller.I'm having some problems with this. 我正在使用一个诺言从服务中的json获取数据,然后将其传递给我的控制器,对此我遇到了一些问题。

That's my Service 那是我的服务

getMetaData: function () {
            var defer = this.$q.defer();
            this.$http.get('http://localhost:8084/login-api/public/metadata/describe/Coisa')
                    .success(function (data, status, headers, config) {
                        defer.resolve(data)
                    })
                    .error(function (data, status, headers, config) {
                        defer.reject(status);
                    })
            return defer.promise;

        }

And here i'm calling the Service im my controller 在这里,我称服务为我的控制器

getData: function () {
            this.$scope.meta = this.EntityService.getMetaData();
            var dataS = {};
            this.$scope.meta.then(
                    function (data) {
                        this.$scope.metaD = data;
                    },
                    function (err) {
                        alert('Error');
                    }
            )
        }

And this is the error that I'm having: 这是我遇到的错误:

TypeError: Cannot set property 'metaD' of undefined
at basic-list-controller.js:29
at l.promise.then.l (angular.js:7)
at angular.js:7
at u.$get.u.$eval (angular.js:7)
at u.$get.u.$digest (angular.js:7)
at u.$get.u.$apply (angular.js:7)
at p (angular.js:7)
at T (angular.js:7)
at XMLHttpRequest.b.onreadystatechange (angular.js:7)

And i can't see why i'm having this error. 而且我看不到为什么我有这个错误。 When i log the data on the console, it's there, but i can't give the value to a variable. 当我在控制台上记录数据时,它就在那儿,但是我不能将值赋予变量。

In your success function "this" is not what you expect 在您的成功函数中,“ this”不是您期望的

function (data) {
    this.$scope.metaD = data;
}

You can try setting this outside your callback like this: 您可以尝试在回调之外设置此代码,如下所示:

var _this = this;

and inside your callback use: 在您的回调中使用:

function (data) {
    this.$scope.metaD = data;
}

Your final code should look like: 您的最终代码应如下所示:

getData: function () {
        var _this = this;
        this.$scope.meta = this.EntityService.getMetaData();
        var dataS = {};
        this.$scope.meta.then(
                function (data) {
                    _this.$scope.metaD = data;
                },
                function (err) {
                    alert('Error');
                }
        )
    }

There are a number of things wrong with how you approach this. 您如何处理此问题有很多错误。

First: you don't need to use $q.defer for something that already returns a promise, like $http - this is considered a deferred anti-pattern . 首先:您不需要将$q.defer用于已经返回承诺的内容,例如$http这被认为是延迟的反模式

Second: avoid passing $scope to your service - it makes it more difficult to test and upsets separation of concerns. 第二:避免将$scope传递给您的服务-这将使测试变得更加困难,并且不利于分离关注点。 $scope belongs to the controller. $scope属于控制器。

And so, your service can be made much simpler. 因此,您的服务可以变得更加简单。 You don't even need two methods - since both return the same thing 您甚至不需要两个方法-因为两者都返回相同的内容

.factory("myDataService", function($http){
    return {
       getMetaData: function(){
          return $http.get('url/to/data');
       }
    };
}


.controller("MainCtrl", function($scope, myDataService){
   myDataService.getMetaData()
      .then(function(data)){
         $scope.metaD = data;
      });
}

You can simplify it to this because using a $http service can return a promise directly and use the 'then' function to pre-process data before returning it: 您可以简化为它,因为使用$ http服务可以直接返回promise,并使用'then'函数对数据进行预处理,然后再返回:

getMetaData: function () {
            return $http.get('http://localhost:8084/login-api/public/metadata/describe/Coisa')
                    .then(function (success) {
                        return success.data;
                    },
                      function (error) {
                        return error;
                    });
        }

This should now work with the rest of your code. 现在,这应该可以与其余代码一起使用。 Note I return the entire result, if you just want the response then return 'succes.data'. 请注意,如果您只想响应,我将返回整个结果,然后返回“ succes.data”。 Or you can check for it on controller code. 或者,您可以在控制器代码上进行检查。

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

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