Encountering an issue in AngularJS where a necessary dependency cannot be resolved while attempting to utilize a global service

In order to streamline my code, I decided to create a service for a function that is utilized in multiple controllers.

To achieve this, I added a commonService.js file to my index.html

'use strict';
var myApp = angular.module('myAppName');
myApp.service(['loadHttpService', '$window', '$http', function (loadHttpService, $window, $http) {
    this.loadHttpService = function (url) {
        ...
        };
        return $http.jsonp(url, {
                params: {
                    callback: "JSON_CALLBACK"
                }
            })
            .then(function (response) {
                ...
            });    
    };
}]);

I then proceeded to use this service in my homeController by including it as a dependency:

'use strict';    
angular.module('Home') 
.controller('HomeController', ['$scope', '$rootScope', '$http', '$window', '$state', 'loadHttpService',   
    function ($scope, $rootScope, $http, $window, $state, loadHttpService) {
        ...
        var url = "http://xxx";
        loadHttpService.loadHttp(url);

    }]);

However, I encountered an error message https://docs.angularjs.org/error/$injector/unpr?p0=loadHttpServiceProvider%20%3C-%20loadHttpService%20%3C-%20HomeController

I am unsure why this error is occurring and how to resolve it. Any tips on improving this setup would be greatly appreciated, as I am relatively new to angularjs.

Please note: myAppName is the name of my app (used in ng-app).

Answer №1

There are many different approaches to achieving a goal, just like there are multiple ways to accomplish a task or handle dependencies.

module1 - common

angular.module('commonServices', [])
  .service('myService', function () { //this is an example service})

module2

angular.module('superApp', ['commonServices'])
  .controller('notMyCtrl', function (myService) { //using a service from another module})

module3

angular.module('homeApp', ['commonServices'])
  .controller('homeCtrl', function (myService) { //utilizing a service from another module})

Alternatively, you can also inject the home module into the parent module (though the benefits of bootstrapping two apps on one page may be unclear).

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

How to properly cast interfaces when using Angular 4's HttpClient to fetch items

Here is the layout of my interface interface IPlacesResult { summary: { queryTime: number; // ... }; results: { id: string; // ... address: { streetNumber: number; // ... }; }[]; } To populate this interface, I ...

React components receive props as an empty array when they are being passed to the component

I am passing a state to a component as a prop in the following way: componentDidMount() { axios.get("path/to/data") .then(result => { this.setState({ receivedData: result.data, }); ...

Unable to transfer file using ajax (displaying print_r($_FILES); Array ( ) )

I have encountered an issue with sending a file using XHR compared to a common form confirmation. Here is the HTML code: <form action="ajax/upload.php" method="post" name="form1" enctype="multipart/form-data" id="id1"> <input type="file" name=" ...

Change the position of a div by clicking on different content menu buttons to make it go up

I have implemented move up and move down buttons in my context menu for multiple div drops. However, I am facing an issue with moving the div down after clicking the move down button. Here is the code snippet that I am currently using: $(".propertyClass" ...

When I upload a file using v-file-input, it displays two names

While working with nuxt, I made an interesting discovery. See the pattern here The top name is the file that was uploaded, and the bottom one is the target file name. I plan to remove the bottom name and replace it with the top. This is what I envision: E ...

Disconnect occurred during execution of Node.js "hello world" on a Windows 7 operating system

Issue Resolved: Oh no! jimw gets 10000 points for the solution! I've decided to delve into a hobby project using Node.js. Here's where I started: Downloaded and installed Node version 0.6.14 Copied and pasted the classic "hello world" program ...

What steps do I need to take to ensure this function runs sequentially? Perhaps my understanding of async and await is lacking

I have a function that is responsible for adding data to my database. However, I'm encountering some inconsistency where it works sometimes and fails other times. My suspicion is that the eDataBuilder function is taking too long to iterate through the ...

Eliminate items from a list that have duplicate properties

I have a collection of objects, each with a unique NAME property. However, there are duplicates in the collection where some objects share the same NAME. const arr = [ {name: "x", place: "a", age: "13" }, {name: "x", place: "b", age: "14" }, { ...

Tips for duplicating a collada model in three.js?

I've imported a .dae model into my scene and I want to use it multiple times. The code provided works with meshes, but the collada.scene object is not a mesh: var mesh2 = new THREE.Mesh( loadedMesh.geometry, loadedMesh.material ); Is there a way to ...

What is the best way to create an animation where every letter in a word transitions to a different

Is there a way to animate a word so that each letter changes color within a range of 7 colors, with all letters displaying different colors simultaneously in an infinite loop? <div class="box"> <h1 class="logo animate__animated an ...

How to make Angular 5 wait for promises to finish executing in a for loop

My task involves working with an array like this: arr = ['res1', 'res2', 'res3']; For each value in the arr, I need to make an API call that returns a promise. arr.forEach(val => this.getPromise(val)); The getPromise me ...

Using JavaScript (AJAX), learn the process of incorporating XML data within HTML files

I'm relatively new to HTML and I'm attempting to create a self-contained HTML page that includes all necessary CSS, data, and JavaScript within the file itself. While I understand that this will result in a rather messy HTML document, it is essen ...

How can I access dynamically created input elements without using $refs, such as getting focus?

Is there a way to handle dynamically created inputs for editing purposes without using jQuery or vanilla JS all the time? Each input element has its own ID and is displayed through v-if when editing is triggered. However, Vue does not recognize them in r ...

How to Utilize Vue and Checkboxes for Filtering a List?

My current challenge involves filtering a list of posts based on userId using checkboxes. The data is being retrieved from: https://jsonplaceholder.typicode.com/posts. I aim to include checkboxes that, when selected, will filter the list by userId. Here is ...

Newly included JavaScript file displays on view page, but triggers a 404 error when attempting to open

Once I implemented the following code in the child theme's function.php file: add_action('wp_enqueue_scripts', 'js_files'); function js_files() { wp_register_script('ajax_call_mkto', get_template_directory_uri() . ' ...

What is causing JavaScript to be unable to access the width property of textureImage?

I am currently facing an issue while trying to render image texture dynamically. The console is showing an error message: Uncaught TypeError: Cannot read property 'width' of undefined. Some have suggested setting needsUpdate to false, but doing s ...

When utilizing an optional {parameter}, the ui-router state resolve entries are being assessed twice

Why are UI-Router resolve entries reloading twice when using $state.go or ui-sref with an optional parameter that is not filled? .state('dashboard.loan', { url: "/loan/:type/{instanceid}", templateUrl: '/app/dashboard/views/package. ...

Counting the number of times a form is submitted using a submit button and storing the data

After researching for a few hours, I've gathered information on different techniques for storing data related to a submit button counter in a text file. <form action="/enquiry.php" method="post" name="form"> <label>Name *</label> &l ...

Having difficulty invoking another controller within a controller in Angular by utilizing $rootScope, $compile, and $route

mainApp .controller('homeController', function($scope, $http, $timeout, $compile, $rootScope, $routeParams, $location, $route) { //implement functionality here } ); mainApp.controller('ReportsController', function($sc ...

Tips for effectively implementing a custom theme alongside a component library that utilizes Material UI without the need to apply it to every single component

What is the correct way to utilize a custom theme with a component lib that utilizes Material UI without wrapping every single component? import { createMuiTheme } from '@material-ui/core/styles'; const theme = createMuiTheme({ palette: { ...