【问题标题】:AngularJS Variable is UndefinedAngularJS 变量未定义
【发布时间】:2017-07-03 22:17:17
【问题描述】:

所以我的代码是这样的

.controller('weinDetailsCtrl', ['$scope', '$stateParams', '$http', '$rootScope',function ($scope, $stateParams, $http, $rootScope) {

$scope.url = "https://winetastic.azurewebsites.net/tables/Wine/" + $rootScope.actWine + "?ZUMO-API-VERSION=2.0.0";
$scope.Winet;

$http({
    method: "GET",
    url: $scope.url
}).then(function mySucces(response) {

    $scope.wineDetails = response.data;
    $scope.Winet = $scope.wineDetails.Winetype_ID;
    alert($scope.Winet);


}, function myError(response) {
    $scope.wineDetails = response.statusText
});

alert($scope.Winet);}])

第一个警报给了我正确的 WineType_ID,第二个警报给了我一个“未定义”。 怎么了?

【问题讨论】:

  • 第一个警报将是undefine,第二个警报将具有价值
  • 是的,你是对的,但为什么呢?我想用 winet 做进一步的 sutff,但它总是说它是未定义的

标签: angularjs variables scope undefined


【解决方案1】:

在从 REST 调用获取数据之前调用您的第二个警报。这是由于 javaScript 的异步特性。所以你得到的价值是未定义的。

【讨论】:

    【解决方案2】:

    让我澄清一下,您的第一个警报将是 undefined,第二个将具有价值。

    这是因为当它第一次调用时你不会有$scope.Winet 值。一旦你从服务器获得价值,那么它就会有一些价值。这就是 异步 的全部意义所在。

    暂时您可以使用为$scope.Winet 分配一些值。所以第一次警报将是那个值而不是未定义。 试试

    $scope.url = "https://winetastic.azurewebsites.net/tables/Wine/" + $rootScope.actWine + "?ZUMO-API-VERSION=2.0.0";
    $scope.Winet = 'alert before Asynchronous call completion';//you can change it as your need
    

    现在第一次提醒将是alert before Asynchronous call completion

    更多细节可以去这个链接。

    Asynchronous Details

    【讨论】:

      【解决方案3】:

      您的response.data 中似乎未定义Winetype_ID,请检查您的响应数据。我建议使用console.log();,这样你的脚本就不会停止。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2015-09-19
        • 1970-01-01
        • 1970-01-01
        • 2013-06-05
        • 1970-01-01
        • 2011-06-11
        • 2014-05-27
        相关资源
        最近更新 更多