0

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!

2
  • What is your controller code? Commented Jun 8, 2016 at 14:22
  • Hey Niket! It is under copyright, I cannot post it :/ I can tell you that I am working within a HeaderController for the header of the application UI Commented Jun 8, 2016 at 14:35

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

2 Comments

Thank you! I was looking actually for the understanding of $rootscope (did not know about this before). I realized that the data had already been mapped to some $rootscope variables that I was able to use to solve my issue. Thank you for pointing me in the right direction!
Glad to help you mate :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.