简体   繁体   中英

AngularJS and $http get JSON - data is not defined

Hi I am trying to retrieve some data from webservice using AngularJS $http get.

I have the following code snippet:

In the servicesjs:

     .factory('BoothDesignatedCoordsService', ['$http', function ($http) {

var factory = {};

factory.getBoothDesignatedCoords = function (strBoothName, intFloorPlanID) {


 var sendToWS;
 var boothDesignatedCoords

    var JSONObj = {
        BoothName: strBoothName,
        FloorPlanID: intFloorPlanID
    };
    sendToWS = JSON.stringify(JSONObj)

    var urlBase = 'http://localhost:4951/wsIPS.asmx/fnGetBoothDesignatedCoords?objJSONRequest=' + sendToWS;
        return $http.get(urlBase) 
}
return factory;

}])

In the controllerjs:

 var boothDesignatedCoords = BoothDesignatedCoordsService.getBoothDesignatedCoords(strListShortListedBooth[i], 3).success(function (response, data, status) {
        console.log("successfully send booth name and floor plan id to ws");
        console.log("data " + data + " , status : " + status);
        console.log("data " + data);
        boothDesignatedCoords = data;

   for (var c = 0; c < boothDesignatedCoords.length; c += 2) {

   }

The $http get is successful as I am able to print "successfully send booth name and floor plan id to ws" in the browser console log. When I tried to print console.log("data " + data), it gives me some values of an integer array. That is exactly what I want. But in the controller I tried to assign data to the variable boothDesignatedCoords, the program does not run the for loop. Am I missing some code?

EDIT: I tried to trace the code ( trace the variable called "data" in the controllerjs) and it says "data is not defined"

You appear to be confused about the methods available on the $http promise and their arguments. Try this

BoothDesignatedCoordsService.getBoothDesignatedCoords(strListShortListedBooth[i], 3)
.then(function(response) {
  var data = response.data
  var status = response.status

  console.log('data', data) // note, no string concatenation
  // and so on...
})

FYI, the success and error methods have been deprecated for some time and removed from v1.6.0 onwards. Don't use them.

I also highly recommend passing query parameters via the params config object

var urlBase = 'http://localhost:4951/wsIPS.asmx/fnGetBoothDesignatedCoords'
return $http.get(urlBase, {
  params: { objJSONRequest: sendToWS }
})

This will ensure the key and value are correctly encoded.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM