简体   繁体   中英

$templateCache not working in angular-config in Angular.js

I am getting "angular.min.js:6Uncaught Error: [$injector:modulerr]" when trying to use $templateCache in my app.config block, if i remove the $templateCache parameter from app.config then i do not see any errors. Please let me know if i missed out something. Thanks in advance.

 var app = angular.module("app", ['ui.router'], function () { console.log('Application Initiated Successfully...'); }) .run(function ($templateCache, $http) { console.log("app is running"); $http.get("Views/home2.html", { cache: true }).success(function (html) { $templateCache.put("Test.html", html); console.log($templateCache.get("Test.html")); }); console.log($templateCache.info()); }); app.config(['$stateProvider', '$urlRouterProvider', '$locationProvider', '$templateCache', function ($stateProvider, $urlRouterProvider, $locationProvider, $templateCache) { $urlRouterProvider.otherwise("/"); $stateProvider .state("/", { url: "/", templateUrl: "Views/home.html" }); }]); app.controller("indexController", ["$rootScope", "$scope", function ($rootScope, $scope) { console.log('indexController'); $scope.message = "Hi lets get started..."; } ]); 

You cannot access service at time of angular config. You can access your service inside your app.run block. $templateCache is a service that you are trying to use in your config block.

However, You can access it inside your resolve block of a state.

$stateProvider
        .state("/", {
            url: "/",
            templateUrl: "Views/home.html",
            resolve: {
              data: function ($templateCache,dbService) {
              return dbService.getData();
            }
        });

You can only access providers at time of config block of an angular.

Find below link to understand more about config block of angular. https://docs.angularjs.org/guide/module

Below is a description from its official site.

  • Configuration blocks - get executed during the provider registrations and configuration phase. Only providers and constants can be injected into configuration blocks. This is to prevent accidental instantiation of services before they have been fully configured.
  • Run blocks - get executed after the injector is created and are used to kickstart the application. Only instances and constants can be injected into run blocks. This is to prevent further system configuration during application run time.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM