16

See solution below:

I'm trying to connect to a Parse.com Rest backend and display data from object values.

HTML (I put several angular calls to be sure to catch output):

<div ng-controller="MyController">
    <p>{{item}}<p>
    <p>{{items}}<p>
    <p>{{item.firstName}}<p>
    <p>{{data}}<p>

</div>

JAVASCRIPT rest:

function MyController($scope, $http) {

    $scope.items = [];
    $scope.getItems = function() {

        $http({method : 'GET',url : 'https://api.parse.com/1/classes/Professional/id', headers: { 'X-Parse-Application-Id':'XXXX', 'X-Parse-REST-API-Key':'YYYY'}})
            .success(function(data, status) {
                $scope.items = data;
            })
            .error(function(data, status) {
                alert("Error");
            });
    };
}

This won't work, it does strictly nothing, not even a message in the console. I know the rest call got the correct credential, as I'm able to get object content returned when I test it with a rest tester program. Maybe the URL should not be absolute ? Any clue is very welcome, i've spent DAYS on that.

SOLUTION:

Thanks to the help of people answering this thread, I was able to find the solution to this problem so I just wanted to contribute back:

Get Json object data from Parse.com backend, pass it authentification parameters:

function MyController($scope, $http) {

    $scope.items = [];
    $scope.getItems = function() {

        $http({method : 'GET',url : 'https://api.parse.com/1/classes/Professional', headers: { 'X-Parse-Application-Id':'XXX', 'X-Parse-REST-API-Key':'YYY'}})
            .success(function(data, status) {
                $scope.items = data;
            })
            .error(function(data, status) {
                alert("Error");
            });
    };

Notice that ' ' necessary arround header key object values. Those ' ' are not necessary around method and url keys.

Template that list all 'firstName' of each object:

<div ng-controller="MyController" ng-init="getItems()">
     <ul>
        <li ng-repeat="item in items.results"> {{item.firstName}} </li>
    </ul>
</div>

Notice: "item in items.results". "results" is necessary because the return value is a JSON object that contains a results field with a JSON array that lists the objects. This could save you some headache. Also notice "ng-init": if you don't put that, or any other form of call to the getItem(),then nothing will happen and you will be returned no error.

That was my first try of Angularjs, and i'm already in love ^^.

Cœur
  • 37,241
  • 25
  • 195
  • 267
Benj
  • 329
  • 1
  • 4
  • 11
  • 1
    Have you tried anything? At least show us some of the code in your controller. Hint: you have to inject the "$http" service in your controller. – NicolasMoise Nov 08 '13 at 15:50
  • You should be able to use Parse Javascript SDK from your controller and update $scope.items with the data and you may want to look at this https://github.com/jimrhoskins/angular-parse – Prasad K - Google Nov 08 '13 at 15:56
  • Thanks for link, but I want to avoid using any third party SDK, and directly interpret Restful data. – Benj Nov 08 '13 at 16:01
  • Then you can use angularjs $http and re-invent the wheel :) – Prasad K - Google Nov 08 '13 at 16:03
  • Definitely read about $http like @NicolasMoise said. You can do a GET request with a callback to set your $scope.item object. – Zack Argyle Nov 08 '13 at 16:09
  • The angular-parse is written in coffee script, and converting to JS gots awfully complicated code, sorry i'm not an expert. I read the $https doc of angular, what i don't get, is how to pass for example additional parameters, such as the app id and api key, or any other parameter. – Benj Nov 08 '13 at 16:10
  • @Benj Again, it's hard to help you if you don't show us what you've attempted, even if it doesn't work. Plus, who knows? by trying you might actually solve the problem yourself :) – NicolasMoise Nov 08 '13 at 16:18
  • Ok, I updated post of what I'm trying. I think it start to go wrong at url I point.... should it be relative or full url, also, how to integrate the custom app id and key into the code ? – Benj Nov 08 '13 at 16:30
  • 1
    `$http({method: 'GET', url: 'https://api.parse.com/1/classes/Professionals', headers: {X-Parse-Application-Id: 'xxx', X-Parse-REST-API-Key: 'yyy'}})` – m.e.conroy Nov 08 '13 at 17:05
  • m.e.coroy, thanks I'm going to try this. Should I put your line inside a MyController function ? – Benj Nov 08 '13 at 17:14
  • Could it be not working because I test on local PC ? – Benj Nov 08 '13 at 20:34

3 Answers3

14

Based in your request the controller should be:

HTML

<div ng-controller="MyController">
    <button type="button" ng-click="getItems()">Get Items</button>
    <ul>
       <li ng-repeat="item in items"> item.firstName </li>
    </ul>
</div>

JS

  function MyController($scope, $http) {
        $scope.items = []

        $scope.getItems = function() {
         $http({method : 'GET',url : 'https://api.parse.com/1/classes/Users', headers: { 'X-Parse-Application-Id':'XXXXXXXXXXXXX', 'X-Parse-REST-API-Key':'YYYYYYYYYYYYY'}})
            .success(function(data, status) {
                $scope.items = data;
             })
            .error(function(data, status) {
                alert("Error");
            })
        }
    }
DinoMyte
  • 8,737
  • 1
  • 19
  • 26
Adrian
  • 491
  • 3
  • 15
  • Thanks shouldn't I name the function MyController instead of ParseCtrl ? That's the name of the controler I chose in my html. – Benj Nov 08 '13 at 18:15
  • 1
    @Benj Yes, you can name the function `MyController`, I already did it in the answer. – Adrian Nov 08 '13 at 19:01
  • Thanks, I edited the above message as it still won't work. Note that I had to put '' between header keys names. That is bizzare, but it would be marked as wrong code in editor I use. – Benj Nov 08 '13 at 19:07
  • 1
    @Benj, What is the response from the server? Did you check it with firebug or Chrome Developer Tools? – Adrian Nov 08 '13 at 19:26
  • Adrian, there is strictly nothing in the console, or in the network monitoring... i'm puzzled – Benj Nov 08 '13 at 19:59
  • Hi, this makes lots of difference. I can't see exactly what I want, but when I put the console log, I can correctly log first name of that object !!! I think I can tweak that to get what I want. Please explain why the click trigger makes such a difference ? – Benj Nov 08 '13 at 21:09
  • 1
    The $http request is executed when you click, not before. The response of the $http service is a promise so you can't assign it to a variable directly. For a better connection with angular and RESTful API I always use ngResource. Please could you tell how I have to modified the answer to respond to your question. – Adrian Nov 08 '13 at 21:39
  • Thanks for your help. The return value is a JSON object that contains a results field with a JSON array that lists the objects as you can see here: https://www.parse.com/docs/rest#queries the result which contains 2 objects. Problem is that ng-repeat iteration won't work in this case, for example if I try to repeat and display all the 'playerName'. – Benj Nov 08 '13 at 21:56
  • It's ok I managed to get exacly what I wanted. Only thing to change was 'item in items.results'. My last question is, how should I change this to have it loaded without a click ? Should I use ngResource ? How ? – Benj Nov 08 '13 at 22:11
1

Just a little update to the newer versions of Angular (using .then since version 1.5):

myApp.controller('MyController', function($scope, $http) {

  $scope.items = []

  $http({
     method: 'GET',
     url: 'https://api.parse.com/1/classes/Users',
     headers: {'X-Parse-Application-Id':'XXXXXXXXXXXXX', 'X-Parse-REST-API-Key':'YYYYYYYYYYYYY'}
  })
    .then(function successCallback(response) {
        alert("Succesfully connected to the API");
        $scope.items = data;
    }, function errorCallback(response) {
        alert("Error connecting to API");
    }); 

});
Kefi
  • 129
  • 1
  • 4
0

var app = angular.module("app",[]);
app.controller("postcontroller", function($scope, $http){
$scope.getAllProjects = function() {
        var url = 'https://reqres.in/api/products';
        $http.get(url).then(
            function(response) {
            $scope.projects = response.data.data;
            },
            function error(response) {
              $scope.postResultMessage = "Error with status: "
                  + response.statusText;
            });
      }
      $scope.getAllProjects(); 
 });
<div ng-app="app">
<div ng-controller="postcontroller">
<div class="panel-body">
    <div class="form-group">
      <label class="control-label col-sm-2" for="project">Project:</label>
      <div class="col-sm-5">
        <select id="projectSelector" class="form-control">
          <option id="id" ng-repeat="project in projects"
             value="{{project.id}}">{{project.name}}</option>
        </select>
      </div>
    </div>
  </div>
 </div>
</div>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.2.16/angular.js"></script>
Sandun Susantha
  • 1,010
  • 1
  • 10
  • 11