Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/angularjs/21.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Angularjs 将值从then函数赋给变量PROMITE_Angularjs_Deferred - Fatal编程技术网

Angularjs 将值从then函数赋给变量PROMITE

Angularjs 将值从then函数赋给变量PROMITE,angularjs,deferred,Angularjs,Deferred,我正在努力得到承诺。因此,我编写了如下示例代码 <!doctype html> <html ng-app="myApp"> <head> <meta charset="UTF-8"> <script src="../angularjs.js"></script> </head> <body> <div ng-controller="CartControll

我正在努力得到承诺。因此,我编写了如下示例代码

<!doctype html>
<html  ng-app="myApp">
  <head>
    <meta charset="UTF-8"> 
    <script src="../angularjs.js"></script>
  </head>
  <body>
    <div ng-controller="CartController">
    </div>

  <script>
    var app = angular.module('myApp', []);

    app.controller('CartController',  function($scope, $q,$http){   

    $scope.newFun = function()
    {
      var defered = $q.defer();
      $http.get('data.json').success(function(data) {
        console.log(data);
        defered.resolve(data);
      })
      .error(function(data, status) {
        console.error('Repos error', status, data);
      });
      return defered.promise;
     }

     var newdata = $scope.newFun().then(
      function(data1) 
      {
        //console.log(data1);
        return data1;
      });

      console.log(newdata);
    });
  </script>
  </body>
</html>

在这里,我试图返回从then函数获得的数据,并将其分配给一个变量。但是我得到了一个$$state对象,它有一个保存数据的值键。直接赋值是可能的,还是在then函数中我需要使用scope对象,然后访问数据???

您的代码有很多问题。。首先,您需要为此使用回调。在您的情况下,因为您使用的是承诺,所以请使用它的API。在它的回调函数中,您可以将数据分配给变量。Angular将通过运行新摘要来完成其余的同步作用域绑定

下一个问题:不要使用$q.defer,你根本不需要它。这是最流行的

还有一件事:不要在控制器中发出任何http请求,这不是合适的位置。相反,将此逻辑移动到可重用服务

总的来说,它看起来像这样:

var app = angular.module('myApp', []);

app.controller('CartController', function ($scope, data) {
    data.get().then(function (data) {
        var newdata = data;
    });
});

app.factory('data', function($http) {
    return {
        get: function() {
            return $http.get('data.json').then(function (response) {
                return response.data;
            }, function (err) {
                throw {
                    message: 'Repos error',
                    status: err.status, 
                    data: err.data
                };
            });
        }
    };
});

newdata是promise对象,您需要在其中一个promise回调中分配范围变量。在这个例子中也不需要使用$q,因为$http本身会返回一个承诺。我很困惑何时使用.then和.success。如果可能的话,您可以简要介绍一下mesucces是functionresponse{return response.data}的一种缩写。我建议始终使用。什么时候才是我应该使用$q.defer的理想情况?如果是非承诺函数,当需要返回承诺时,应该使用defer。像$http、$timeout这样的东西已经返回了承诺,所以您不需要多余的$q.defer。例如,对于不返回承诺的自定义函数,您可以使用它。例如