AngularJS Error: $injector:unpr Unknown Provider

后端 未结 13 907
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-12-13 08:10

I\'m trying to build my own service by following the example in the documentation for the factory methodology. I think I\'ve done something wrong however because I continue

13条回答
  •  北海茫月
    2020-12-13 09:11

    Your angular module needs to be initialized properly. The global object app needs to be defined and initialized correctly to inject the service.

    Please see below sample code for reference:

    app.js

    var app = angular.module('SampleApp',['ngRoute']); //You can inject the dependencies within the square bracket    
    
    app.config(['$routeProvider', '$locationProvider', function($routeProvider, $locationProvider) {
      $routeProvider
        .when('/', {
          templateUrl:"partials/login.html",
          controller:"login"
        });
    
      $locationProvider
        .html5Mode(true);
    }]);
    
    app.factory('getSettings', ['$http', '$q', function($http, $q) {
      return {
        //Code edited to create a function as when you require service it returns object by default so you can't return function directly. That's what understand...
        getSetting: function (type) { 
          var q = $q.defer();
          $http.get('models/settings.json').success(function (data) {
            q.resolve(function() {
              var settings = jQuery.parseJSON(data);
              return settings[type];
            });
          });
          return q.promise;
        }
      }
    }]);
    
    app.controller("globalControl", ['$scope','getSettings', function ($scope,getSettings) {
      //Modified the function call for updated service
      var loadSettings = getSettings.getSetting('global');
      loadSettings.then(function(val) {
        $scope.settings = val;
      });
    }]);
    

    Sample HTML code should be like this:

    
    
        
            Sample Application
        
        
            
    Your UI elements go here

    Please note that the controller is not binding to an HTML tag but to the body tag. Also, please try to include your custom scripts at end of the HTML page as this is a standard practice to follow for performance reasons.

    I hope this will solve your basic injection issue.

提交回复
热议问题