$成功从AngularJS回拨功能 [英] $success call back function from AngularJS

查看:169
本文介绍了$成功从AngularJS回拨功能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我打电话控制器来获取API值。我如何通过阵列的$ HTTP方法之外吗?

I am calling the controller to get the API value. How do I pass the array outside of the $http method?

我需要通过一个数组, PA [] ,到 $ scope.myData = PA;

I need to pass an array, pa[], to the $scope.myData = pa;.

首先,执行console.log(PA)输出值[10,20,30,40]。

First, console.log(pa) prints the value [10,20,30,40].

二,执行console.log(PA)清空数组[]。

Second, console.log(pa) empties array[].

function Ctrl($scope, $http) {
    var url = "https://spreadsheets.google.com/feeds/list/0AsXjbsnPIu06dGswZUV4WX/values?alt=json-in-script&callback=angular.callbacks._0";
    var pa = [];
    $http({
        method: 'JSONP',
        url: url
    }).success(function (data) {

        for (i = 0; i < data.feed.entry.length; i++) {
            var entry = data.feed.entry[i];
            pa.push(entry.gsx$productivity.$t);
            console.log(pa); //[10,20,30,40,50]
        }
    });

    console.log(pa) // [] empty array

    $scope.myData = pa;
}

我如何获得阵列的$成功回调函数之外吗?

How do I get the array outside of the $success callback function?

推荐答案

这code是异步的。 每年之前,被分配到 $ scope.myData $ HTTP 服务有机会从你的API调用获得的价值。

This code is asynchronous. pa is assigned to $scope.myData before the $http service has had a chance to get the value from your API call.

您需要使用 $ Q 服务承诺库来控制你的code的流量。事情是这样的:

You need to use the $q service promise library to control the flow of your code. Something like this:

function Ctrl($scope, $http, $q) {
  var url = "https://spreadsheets.google.com/feeds/list/0AsXjbsnPIu06dGswZUV4WX/values?alt=json-in-script&callback=angular.callbacks._0";
  var pa = [];
  var paPromise = $q.defer()

  $http({
    method: 'JSONP',
    url: url
  }).success(function(data) {

      for (i = 0; i < data.feed.entry.length; i++) {
        var entry = data.feed.entry[i];
        pa.push(entry.gsx$productivity.$t);
        console.log(pa); //[10,20,30,40,50]
      }
      paPromise.resolve(pa)
    });

  $scope.myData = paPromise.promise;
}

在这里,我们注入 $ Q 服务,并用它实例化一个变量 paPromise 。接下来,我们给这个承诺 $ scope.myData 。一旦承诺得到了 $ HTTP 成功方法内部解决,AngularJS会通知你的 $范围和更新的价值和它会在你的模板/ DOM中反映出来。

Here, we inject the $q service and instantiate a variable paPromise using it. Next, we give this promise to $scope.myData. Once the promise gets resolved inside the $http success method, AngularJS will notify your $scope and update the value and it'll be reflected on your template/DOM.

这篇关于$成功从AngularJS回拨功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆