Ronald Peroutka
Ronald Peroutka

Reputation: 25

AngularJS Variable is Undefined

So my code looks like this

.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);}])

the first alert gave me the right WineType_ID, the second alert give me an 'Undefined'. What's wrong?

Upvotes: 0

Views: 1432

Answers (3)

Roger K
Roger K

Reputation: 101

It appears that Winetype_ID is undefined in your response.data, check your response data. And I'd suggest using console.log(); so your script doesn't halt.

Upvotes: 0

Saurabh Agrawal
Saurabh Agrawal

Reputation: 7739

Let me clear you your first alert will be undefined and second will be having value.

This is because you will not have $scope.Winet value when it will call for first time. Once you get the value from the server then it will have some value. This is what Asynchronous is all about.

For time being you can use assign some value to $scope.Winet. so first time alert will be that value instead of undefined. Try

$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

Now first time alert will be alert before Asynchronous call completion.

More detials you can go to this link.

Asynchronous Details

Upvotes: 0

Sumit Sinha
Sumit Sinha

Reputation: 329

Your second alert is called before getting data from REST call. This is due to the asynchronous nature of javaScript. So you are getting value as undefined.

Upvotes: 1

Related Questions