Reputation: 23
I am fairly new to using JavaScript in relation to Angular 2.0. I have about 2 years of experience with Java, so I'm familiar with programming (in general).
In my application, I have a JSON payload whose data I would like to access. Normally, in Java, I might make a map to capture said data.
My question: How does one capture data in Angular (2.0) to be used within the scope of a controller/service?
Sample Data:
"impairments":[
{
"type":"SUCKOUT",
"lowBin":132000000,
"highBin":210000000,
"severity":57
}
In which I am trying to use the data for "type"
Thanks so much!
Upvotes: 0
Views: 84
Reputation: 1105
First of all your JSON data doesn't look correct. Assuming a get request to /some/endpoint/here
in your app returns:
{
"impairments": [
{
"type":"SUCKOUT",
"lowBin":132000000,
"highBin":210000000,
"severity":57
}
]
}
You can use a simple controller like:
app.controller("yourController", ['$http', '$scope', function($http, $scope) {
$scope.type = null;
$http.get('/some/endpoint/here').then(
function(response) {
//response.data contains all the response data
$scope.type = response.data.impairments[0].type;
},
function() {
//error occured, do something
}
);
}]);
Then in your controller you can simply use:
{{type}}
PLEASE NOTE
For security reasons, angularJS advices to prefix all the JSON response with )]}',\n
and angular strips it off.
A JSON vulnerability allows third party website to turn your JSON resource URL into JSONP request under some conditions. To counter this your server can prefix all JSON requests with following string ")]}',\n". Angular will automatically strip the prefix before processing it as JSON.
You can read more at: https://docs.angularjs.org/api/ng/service/$http#security-considerations
Upvotes: 1