AngularJS + $ q,在多个ajax调用完成后执行某些操作

Chr*_*tis 7 javascript ajax angularjs angular-promise

我需要在页面加载时加载一些数据,然后执行任务.为了获得我想要的数据,我执行多个不同的ajax调用.但是为了执行任务,我需要所有人确保所有的ajax调用都已完成.这是我到目前为止所做的:

$q.when(
        $http.get('url1').success(function (data) {
            $scope.data1 = data;
            console.log("ajax1 finished");
        }),
        $http.get('url2').success(function (data) {
            $scope.data2 = data;
            console.log("ajax2 finished");
        }),
        $http.get('url3').success(function (data) {
            $scope.data3 = data;
            console.log("ajax3 finished");
        }),
        $http.get('url4').success(function (data) {
            $scope.data4 = data;
            console.log("ajax4 finished");
        })
    ).then(
        console.log("All ajax calls have finished!"),
        executeTask()
    );
Run Code Online (Sandbox Code Playgroud)

我的问题是在所有 ajax调用完成,块中的代码then(...);不会被执行.我在我的控制台中得到这样的东西:

ajax2 finished
ajax1 finished
All ajax calls have finished!
ajax3 finished
ajax4 finished
Run Code Online (Sandbox Code Playgroud)

我一定做错了什么.我怎样才能让它按照我想要的方式工作?


编辑:我尝试了以下,就像答案中提到的那样,但我仍然面临同样的问题.

$q.all([
    $http.get('url1').then(function (data) {
        $scope.data1 = data;
        console.log("");
    }),
    $http.get('url2').success(function (data) {
        $scope.data2 = then;
        console.log("ajax2 finished");
    }),
    $http.get('url3').then(function (data) {
        $scope.data3 = data;
        console.log("ajax3 finished");
    }),
    $http.get('url4').then(function (data) {
        $scope.data4 = data;
        console.log("ajax4 finished");
    })
]).then(
    console.log(""),
    executeTask()
);
Run Code Online (Sandbox Code Playgroud)

mau*_*ycy 14

我用你做了一个工作的plunker $q.all()

http://plnkr.co/edit/JHd3XPTKBxx4KRso5JRB?p=preview

  $q.all([
    $http.jsonp('http://ip.jsontest.com/?callback=JSON_CALLBACK').then(function(response) {
      $scope.ip.one = response.data
      console.log('one')
    }),
    $http.jsonp('http://ip.jsontest.com/?callback=JSON_CALLBACK').then(function(response) {
      $scope.ip.two = response.data
      console.log('two')
    }),
    $http.jsonp('http://ip.jsontest.com/?callback=JSON_CALLBACK').then(function(response) {
      $scope.ip.three = response.data
      console.log('three')
    }),
    $http.jsonp('http://ip.jsontest.com/?callback=JSON_CALLBACK').then(function(response) {
      $scope.ip.four = response.data
      console.log('four')
    }),
  ]).then(function() {
    console.log('all')
  })
Run Code Online (Sandbox Code Playgroud)