Mysterious Source within AngularJS $resource

I have been encountering the error of unknown provider, and have explored various solutions but I feel like there is something missing:

app.js

var myApp = angular.module('myApp', [
    'ngResource',
    'myAppControllers',
    'myAppServices',
    'myAppFilters'
]).config([
    '$locationProvider',
    function(
        $locationProvider) {

        $locationProvider.html5Mode({
            enabled: true,
            requireBase: false,
            rewriteLinks: false
        });
    }]);

var myAppControllers = angular.module('myAppControllers', []);

var myAppServices = angular.module('myAppServices', []);

var myAppFilters = angular.module('myAppFilters', []);

Item.js

myAppServices.factory('Item',
    function($resource) {
        return $resource('/api/items/:id');
    });

ItemService.js (1)

myAppServices.factory('itemService',
    function($q,
             $http,
             Item) {

        return {
            delete: function(id){

// Item, $q and $http are undefined here

                return Item.delete({id: id}).$promise;
            }
        };
    });

alternative ItemService.js (2)

myAppServices.factory('itemService', [
    '$q',
    '$http',
    'Item', // If I don't inject it here I can use this service with $q and $http
    function($q,
             $http,
             Item) {
        return {
            delete: function(id){
                return Item.delete(id).$promise;
            }
        };
    }]);

And in my controller:

myAppControllers.controller('ItemsCtrl', [
    '$scope',
    'itemService',
    function(
        $scope,
        itemService) {

        var ctrl = this;

        ctrl.ItemService = ItemService;

        ctrl.deleteItem = function(id){

            ctrl.itemService.delete(id)
                .then(function(response){
                    console.log(response);
                }, function (error) {
                    console.log(error);
            });

        };
    }]);
  1. If I follow the approach in (1), I receive an error stating undefined.delete is not a function in itemService.

  2. If I try as described in (2), the app fails to load with:

    Unknown provider: ItemProvider <- Item <- itemService

So what could be the issue?

Answer №1

There are several issues that need to be addressed.

  • It is important to have myAppServices as a dependency of myAppControllers in order to use it within a controller.

    To resolve this, you should do the following:

    var myAppServices = angular.module('myAppServices', []);
    var myAppControllers = angular.module('myAppControllers', ['myAppServices']);
    
  • The Item service in the myAppServices module utilizes $resource, but you have not injected ngResource as a dependency of myAppServices.

You can view your corrected code on plunker without any errors

EDIT: Additionally, ensure that all your files are properly included in index.html!

Answer №2

It seems that in the $resource you are missing an argument; it should be structured like this:

$resource('/api/items/:id', {id:'@id'});

Give (1) another try, as 'undefined' is likely due to this issue.

Additionally, your delete function should be written as follows:

return Item.delete({id : id}).$promise;

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

Getting the WatchPosition update just one time

I have implemented this code to continuously retrieve the first position and I need it to keep doing so. var init = function() { navigator.geolocation.getCurrentPosition(function(position) { new_position = position; }, onEr ...

Retrieving table information using javascript

My goal is to retrieve information from the <td> elements within the following HTML table: <table class="datadisplaytable" summary="This table lists the scheduled meeting times and assigned instructors for this class.."> <caption class="cap ...

Encountering a "Parsing error: Unexpected token, expected ";" " when developing a React application with the provided code

I am currently working on developing a React application, and I have encountered an issue in my app.js file regarding the render function. Despite being new to JavaScript, I am unable to figure out why this error is occurring. Apologies if it is due to a s ...

Tips for combining enable and disable properties in flatpickr.js?

I'm facing a challenge with using both the enable and disable properties in flatpickr.js. The enable property returns a range of dates that should be enabled, but I specifically want to disable certain days within that range, like weekends. datePicker ...

jQuery, Oops! Something went wrong

I have some JavaScript code on my website that is dynamically loading div elements onto the page. I also want to include onmouseenter and onmouseleave event handlers for each div. I have attempted to use jQuery to implement these handlers, but I am encount ...

Javascript/Webpack/React: encountering issues with refs in a particular library

I've encountered a peculiar issue that I've narrowed down to the simplest possible scenario. To provide concrete evidence, I have put together a reproducible repository which you can access here: https://github.com/bmeg/webpack-react-test Here&a ...

Passing a JavaScript variable to PHP within an HTML document: Parsing data from Wikipedia

I am currently working on passing a JavaScript variable named $url to a PHP function in the same HTML file. The idea is that a user inputs a species into a textbox, and the Wikipedia API is called to check if the input matches a Wikipedia page. If a match ...

Sending a request from JavaScript to C# methods using AJAX, with no expected response, within an ASP.NET MVC framework

Setting up the Environment: <package id="jQuery" version="3.2.1" targetFramework="net45" /> <package id="Microsoft.AspNet.Mvc" version="5.2.3" targetFramework="net45" /> Recently, I encountered an issue while trying to send a request from one ...

requirements for ng-model

Can anyone assist me with ng-model? I have an input field where users can select values from an array called 'posters'. The selected value appears in the list. By default, the list displays 'The grand tour'. However, if a user enters a ...

Running a Custom Tab Component in a React Application

I am currently facing an issue with my React app that has multiple tabs. When I click on a specific tab, I want only that tab to render, but currently all tabs are rendering when I click on one. I have used console.log to confirm that all tabs are indeed r ...

Shared variables in Node.js allow for multiple users to access different entry points simultaneously

In the process of transitioning my node-js application from a single-tenant database to a multi-tenant database, I am facing some challenges. The application code is accessed through an express api and various services are run through different entrypoints ...

A guide on how to identify the return type of a callback function in TypeScript

Looking at this function I've created function computedLastOf<T>(cb: () => T[]) : Readonly<Ref<T | undefined>> { return computed(() => { const collection = cb(); return collection[collection.length - 1]; }); } Thi ...

In my Express Javascript application, I recently encountered a challenge where I needed to export a const outside of another

I am currently working with a file named signupResponse.js const foundRegisterUser = function(err, foundUser){ if(!err){ console.log("No errors encountered") if(!foundUser){ if(req.body.password == req.body. ...

Background loading of child application in single-spa

I'm currently working on setting up a Single-Spa micro frontend with Dynamic Module Loading in React. The user journey I have in mind is as follows: Root Application -> Authentication Application -> User Enters Details -> API Call -> Redir ...

Transferring information from a Java file to AJAX

I have a Java class that prints progress as 1%, 2%, 3% of a process. Now, I am looking to utilize AJAX requests to read this progress and update it continuously on the webpage. Unfortunately, I cannot convert the Java file into a servlet since it is being ...

Discover past stock prices on Yahoo Finance

I'm stuck on tweaking a functioning jfiddle example that I have. Can anyone help me with this two-part question regarding the jfiddle: http://jsfiddle.net/maxmillien/qPVSy/ Part 1) Is there a way to clear the search each time a new search is performe ...

Browse through all products with just one click using JQuery!

I am trying to achieve a feature where clicking a 'View all' button under the product sheets will display all the products in alphabetical order by adding clones at the bottom of the page to fill all available spaces. Can you assist me with this? ...

Modifying the value of a property in an object array created using the map method is ineffective

I have a collection of objects: https://i.sstatic.net/XNrcU.png Within the collection, I wished to include an additional property to the objects. To achieve this, I utilized the map function: returnArray = returnArray.map((obj) => { obj.active = "fal ...

The timer does not stop running even after navigating to a different page

Currently, I am utilizing the yo:angular-fullstack generator for developing my website. After a user registers on the site, an activation email is sent containing a verification link. Upon clicking the link, a message confirming successful activation is di ...

Ways to access data attributes during a Bootstrap 4 popover event

Here is the scenario I am facing. When the popover button is clicked, it triggers the following code: <a href="#" id="popover" data-plan-type="2" data-toggle="popover" data-html="true" data-placement="bottom"> <i class="fal fa-plus-circle">&l ...