pmp
pmp

Reputation: 13

AngularJS $http.get returns undefined

I'm building a small angular application. I've started from here: https://github.com/angular/angular-seed. I've changed only the following files:

  1. /app/view1/view1.js 'use strict';

    angular.module('myApp.view1', ['ngRoute'])
    
    .config(['$routeProvider', function($routeProvider) {
      $routeProvider.when('/view1', {
        templateUrl: 'view1/view1.html',
        controller: 'View1Ctrl'
      });
    }])
    
    
    .controller('View1Ctrl', ['$scope', '$http',
      function ($scope, $http) {
        $http.get('/app/data/events.json').success(function(data) {
          $scope.events = data.record;
        }).error(function(data, status){
            alert("error "+data+' | '+status);
        });
    
        $scope.orderProp = 'date';
      }]);
    
  2. /app/view1/view1.html

    p>Available Events</p>
    
    <div ng-controller="EventListController">
      <ul>
        <li ng-repeat="event in events">
            <p>{{event.name}}</p>
            <div>{{event.location}}</div>
            <div>{{event.description}}</div>
            <div>{{event.date}}</div>
    
        </li>
    
      </ul>
    
     <p>Total number of events: {{events.size}}</p>
    </div>
    

When the page is displayed I get the following message:

"error undefined | undefined".

I've checked the code several times and I did not find why the json file is not loaded. If I try to access http://localhost:8000/app/data/events.json in browser the json data is loaded.

The question is: why json file is not loaded?

Upvotes: 1

Views: 8619

Answers (1)

Furkan Başaran
Furkan Başaran

Reputation: 1947

You should use $http methods like below:

// Simple GET request example:
$http.get('url').then(function successCallback(response) {
    // this callback will be called asynchronously
    // when the response is available
  }, function errorCallback(response) {
    // called asynchronously if an error occurs
    // or server returns response with an error status.
  });

Variables in your code data and status are undefined.

You should update your code like this:

 $http.get('/app/data/events.json')
 .then(function successCallback(response) {
      $scope.events = data.record;
  },
  function errorCallback(response) {
      alert(response);
  });

It's will be solve your problem.

Upvotes: 2

Related Questions