krsna
krsna

Reputation: 4333

Unable to figure out what's happening here in $http.get - Angular

I'm a newbie to Angular JS. I was referring Online tutorials and came across the $http service.

(function () {
    "use strict";

    angular
        .module("ngClassifieds") // referring module which is already created
        .controller("classifiedsCtrl", function ($scope, $http) {

            $http.get('data/classifieds.json')
                .then(function(classifieds){
                    $scope.classifieds = classifieds.data;

                })
        });
})(); 

In this piece of code, I'm not able to figure out these lines. Can anyone explain what actually happens here ?

  $http.get('data/classifieds.json')
     .then(function(classifieds){
         $scope.classifieds = classifieds.data;
     }


I have this data in my data/classifieds.json file.

My question is, what exactly the data referred in classifieds.data is ?

Upvotes: 0

Views: 80

Answers (2)

scriobh
scriobh

Reputation: 890

A simple get request example from AngularJS Docs.

$http({
  method: 'GET',
  url: '/someUrl'
}).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.
  });

In your code,

$http.get('data/classifieds.json') // This is the URI of your json file
     .then(function(classifieds){ // Success callback
         $scope.classifieds = classifieds.data; // Here, you are assigning response's data into $scope.classifieds
     }

Upvotes: 1

Carlos Arauz
Carlos Arauz

Reputation: 805

$http returns a promise, it's an asynchronous call, angular use a fork of a library called Q for promises, you can see $q documentation here: https://docs.angularjs.org/api/ng/service/$q. When the promise is fulfilled, that means, the asynchronous call is complete, the .then method call success or error callback depending on the result of the async call.

.then(successCallback, [errorCallback], [notifyCallback]) – regardless of when the promise was or will be resolved or rejected, then calls one of the success or error callbacks asynchronously as soon as the result is available. The callbacks are called with a single argument: the result or rejection reason. Additionally, the notify callback may be called zero or more times to provide a progress indication, before the promise is resolved or rejected.

The argument passed to the success callback is an object with the information about the request response. The data property contain the body of the response, in other way, all the content of data/classifieds.json file (in your case), therefore, $scope.classifieds will contain the json returned by data/classifieds.json.

Here a friendly article about promises and $q: http://www.dwmkerr.com/promises-in-angularjs-the-definitive-guide/

Upvotes: 2

Related Questions