Md. Alauddin
Md. Alauddin

Reputation: 1

In AngularJS -$http.get error : $http.get() is not a function

I want to show the details of the image in which template Id is matched. For this, I use this code and get the error.

controller('TemplateDetailsCtrl',
         ['$scope', '$routeParams','$filter','$http',
  function($scope, $routeParams, $http, $filter) {
    var templateId = $routeParams.templateId;
    $http.get('json/templates.json').then(function(response){
      data = response.data
      $scope.template = $filter('filter')(data, function(d){
        return d.id == templateId;
      })[0];
    });
    $scope.mainImage = $scope.template.images[0].name;
}]); 

Error:

TypeError:

$http.get is not a function
at new <anonymous> (templates.js:25)
at Object.instantiate (angular.js:5137)
at $controller (angular.js:11688)
at Object.link (angular-route.js:1251)
at angular.js:1365
at invokeLinkFn (angular.js:11235)
at nodeLinkFn (angular.js:10554)
at compositeLinkFn (angular.js:9801)
at publicLinkFn (angular.js:9666)
at lazyCompilation (angular.js:10080) "<div ng-view="" class="ng-scope">"

Upvotes: 0

Views: 73

Answers (3)

milad shafiei
milad shafiei

Reputation: 286

$http({url: "json/templates.json",
       method: "GET",
       params: undefined
       }).then(function(response){
           data = response.data
           $scope.template = $filter('filter')(data, function(d){
             return d.id == templateId;
       });

Upvotes: 0

Kamila
Kamila

Reputation: 399

As already mentioned, your dependency injection is wrong.

Order of injections here: ['$scope', '$routeParams','$filter','$http'

have to match order in here: function($scope, $routeParams, $http, $filter)

What more, I recommend you to take a look at the code guidelines for AngularJs, which are very well described here: https://github.com/johnpapa/angular-styleguide/tree/master/a1

Your controller would look like:

(function(){
    'use strict';

    angular.module('app').controller("TemplateDetailsCtrl", TemplateDetailsCtrl);

    TemplateDetailsCtrl.$inject = ['$scope', '$routeParams','$filter','$http'];

    function TemplateDetailsCtrl($scope, $routeParams, $filter, $http) {
        var vm = this;
        // your code
    }
})();

Such approach really makes the code much more readable and easier to maintain

Upvotes: 1

georgeawg
georgeawg

Reputation: 48968

The dependency annotation is in the wrong order:

controller('TemplateDetailsCtrl',
         ̶[̶'̶$̶s̶c̶o̶p̶e̶'̶,̶ ̶'̶$̶r̶o̶u̶t̶e̶P̶a̶r̶a̶m̶s̶'̶,̶'̶$̶f̶i̶l̶t̶e̶r̶'̶,̶'̶$̶h̶t̶t̶p̶'̶,̶
         ['$scope', '$routeParams','$http', '$filter',
  function($scope, $routeParams, $http, $filter) {
    var templateId = $routeParams.templateId;
    //....
}])

The $filter service was being injected in the place of the argument used for the $http service.

For more information, see

Upvotes: 0

Related Questions