Issue: $injector:unpr Angular Provider Not Recognized

I've recently developed an MVC project and encountered an issue regarding the loading of Menu Categories within the layout.

<html data-ng-app="app">
.
.
.
//menu section
<li class="dropdown" ng-controller="menuCategoriesCtrl as vmCat">
  <a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-haspopup="true" aria-expanded="true">Categories<span class="caret"></span> 
  </a>
  <ul id="listaCategorias" class="dropdown-menu" aria-labelledby="dropdownMenu1" ng-repeat="category in vmCat.categories">
    <li>
      <a ng-href="{{category.url}}">
        {{category.Name}}
      </a>
    </li>
  </ul>
 </li>

The app.js file includes:

(function () {

    "use strict";

    angular
        .module('app', ['ngRoute', 'ngAnimate', 'ui.bootstrap']).config(configRoute);

    configRoute.$inject = ['$routeProvider', '$locationProvider'];

    function configRoute($routeProvider, $locationProvider) {
        $routeProvider
            .when('/', {
                templateUrl: 'scripts/app/partials/Home.html',
                controller: 'mainProductsCtrl',
                controllerAs: 'vm'
            })
            .when('/Map', {
                templateUrl: 'scripts/app/partials/Map.html'
            })
            .otherwise({
            redirectTo: '/'
        });

        $locationProvider.html5Mode(false); //.hashPrefix("!")
    }

})();

The controller for the Menu Categories is defined as:

(function() {

    angular.module('app')
        .controller('menuCategoriesCtrl', menuCategoriesCtrl);

    menuCategoriesCtrl.$inject = ['categoryService'];

    function menuCategoriesCtrl(categoryService) {

        var vmCategory = this;
        var listCat = [];

        vmCategory.listCategories = [];

        getListCategories().then(function() {

            for (var i = 0; i < listCat.length; i++) {
                vmCategory.listCategories.push({
                    url: '#/Category/' + listCat.CategoryId + '-' + listCat.Name,
                    categoryName: listCat.Name
                });
            }

        });

        function getListCategories() {
            return categoryService.getCategories()
                .then(function(response) {
                    listCat = response;
                    return listCat;
                })
                .catch(function (response) {
                    return alert('Error ' + response);
                });
        };

    }

})();

Additionally, the service for handling categories is shown below:

(function() {

    var categoriesUri = 'http://localhost/Api/GetCategories';

    angular.module('app')
        .service('categoryService', categoryService);

    categoryService.$inject = ['$http'];

    function categoryService($http) {

        var srvCat = this;

        srvCat.getCategories = getCategories;

        function getCategories() {

            return $http.get(categoriesUri)
                .then(getCategoriesComplete)
                .cath(getCategoriesFail);

            function getCategoriesComplete(response) {
                return response.data;
            }

            function getCategoriesFail(response) {
                return alert('Error ' + response);
            }
        }

    }
})

While trying to run this code in the browser, I encountered an injection error in the controller and the service. Can someone help me understand why?

All required references are correctly included in the bundle in the app_start section.

Thank you in advance

Answer №1

Make sure to call the service function when using the Self Executing function (IIFE pattern). If the function in service.js is not called, it will not bind the service component to the app module. This can result in an error when injecting the service into your code since it is not registered with the app module.

Example:

(function() {

    //service code goes here

})(); <-- Make sure to include () for self calling function

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Is it possible that React.createElement does not accept objects as valid react children?

I am working on a simple text component: import * as React from 'react' interface IProps { level: 't1' | 't2' | 't3', size: 's' | 'm' | 'l' | 'xl' | 'xxl', sub ...

I am having trouble establishing a connection between my Node.js server and the Google Cloud Platform server

I've been working on a global ESP32 Cam project, aiming for worldwide connectivity. I came across a tutorial that has been my guide: https://www.youtube.com/watch?v=CpIkG9N5-JM. I followed all the steps in the tutorial diligently, but unfortunately, I ...

Ways to trigger javascript following each ajax or complete request

I have a jQuery function that attaches a click event to specific elements, as shown below. $(".alert-message .close").click(function(e) { $(this).parent().fadeTo(200, 0, function() { $(this).slideUp(300); }); e.preventDefault(); }) ...

When scrolling on an IOS mobile device, the .on(click) event is triggered for fixed position elements

Whenever I click on an li element or menu, a function is triggered that moves the nav container to the left by the width of the window. However, on my iPhone, after I click to slide the container off the screen, the event gets triggered repeatedly every ti ...

What is the best way to retrieve a style property from a <style> tag using JavaScript?

Is there a way to retrieve CSS properties set in the <style> tag in JavaScript, rather than just those set in the element's style attribute? For example: <style> div{background:red;} </style> How can I access these styles, such ...

Tips for Creating a CSS Radio Button in ASP.NET

I've recently developed a web application using asp.net and I'm facing an issue while trying to style the radio buttons using CSS like the example below: https://i.sstatic.net/k7qGB.jpg However, after applying this design, the radio buttons are ...

Executing intricate MongoDB collection queries using Node.js

I have a vast collection of records stored in MongoDB structured like the following example: { "key" : "a" ,"data" : "value1" , "lastname" : "Doe" }<br> { "key" : "ab" , "data" : "value1" , "lastname" : "Doe" }<br> { "key" : "abc" , "data" : ...

Dealing with cross-domain $.ajax requests and handling 404 errors

Recently, I encountered an issue while trying to retrieve data using $.ajax from an external ASP.NET MVC site (in this case - from my own site). The perplexing part is that the code snippet provided below resulted in a 404 Not Found error, despite the fact ...

Adjust the size of text with jQuery to make it larger or smaller

I run a news website and I'm looking to add buttons that allow users to increase or decrease the font size of the page. I have set a default text size in CSS like this: <style> * { font-size: 12px ; } </style ...

The shared hosting environment encountered an error during the Next JS build process

When I execute the command "npm run build" on my shared hosting server, it throws an error message: spawn ENOMEM. Interestingly, this command runs perfectly fine on my localhost and has been running smoothly on the hosting server for a few weeks until yest ...

Enhancing JavaScript form validation techniques

I am currently working on a user profile form that includes 15 text fields, dropdown menus, and a textarea. Users can input information into these fields, and upon saving the form, not all fields are required to be filled out. However, I need to validate a ...

Implementing HTML page authentication with Identity ADFS URL through JavaScript

I have a basic HTML page that displays customer reports using a JavaScript function. The JavaScript makes an ajax call to retrieve the reports from a backend Spring REST API. In the Spring REST API, I have set up an endpoint "/api/saml" for authentication ...

Exploring nested JSON objects in Angular and rendering them in PHP

On my Json page, I have data organized like this : [{ "qid": "1", "contester": "0", "answer": "0", "question": "What would you do after getting into ...

Guide to selecting a date using JavaScript in Selenium with Ruby

I'm having some trouble selecting a date from a date picker field using JavaScript in Selenium WebDriver. I've attempted the code below, which does navigate to the date window successfully, but I can't figure out how to execute the JavaScrip ...

Exploring the world of JSON manipulation in JavaScript

I've been experimenting with JSON recently and came across something I don't quite understand. Here is an example of some code I used: var str = "{'name':'vvv'}"; var cjson = eval ("(" + str + ")"); alert( ...

Having trouble with Laravel 5.5 and ajax file uploads?

I am encountering an issue with Laravel 5.5 while trying to get an ajax file. I can successfully receive the file using $_FILES, but $request->file() is not working as expected. Here is the code in question. Below are the HTML & Ajax elements: <htm ...

angular8StylePreprocessorSettings

I'm currently trying to implement the approach found on this tutorial in order to import scss files through stylePreprocessorOptions in Angular 8. However, I'm encountering an error stating that the file cannot be found. Any suggestions on how to ...

Error in Firebase Cloud Function: Function did not return the expected Promise or value and instead returned undefined

I've been encountering an issue with my cloud function that triggers on specific database writes (onCreate). It seems to be working fine, but I keep getting an error message stating "Function returned undefined, expected Promise or value" even though ...

Executing an HTML webpage with npm package.json file

I have recently discovered package.json files and am new to using them. I have created an HTML webpage using three files: HTML, CSS, and JavaScript. Currently, I open the HTML file directly in my browser but have been advised to use a package.json file a ...

Sharing Global Variables in Node.js: What's the Best Way to Pass Them into Required Files?

Recently, I decided to organize my gulpfile.js by splitting it into multiple files within a /gulp folder. However, I encountered an issue when trying to pass a variable debug (boolean) into these files to control the behavior of the gulp command being incl ...