Custom service encounters an Angular provider error related to unknown providers

Below is my code for setting up the app and creating a controller:


        var app = angular.module('newstalk',[]);
        
        app.controller("articleCtrl",['$scope','$http','dataService',function($scope,$http,dataService){
            
            $scope.articles = dataService.getArticles();
            
            $scope.commentForm = function(id,userid){
                console.log(userid);
                var uid = userid;
                var c = this.contents;
                var data = {
                    content: c,
                    user: uid
                };
                console.log(data);
                $http.post('/api/article/'+id,data);
            };

        }]);
    

I have also created a service to retrieve data from the server. Here's the code for that:


        (function(){

            angular.module('newstalk')
                .factory('dataService',dataService);

            function dataService(){
                return {
                    getArticles : getArticles
                };

                function getAricles(){
                    console.log("yolo");
                    return $http({
                        method:get,
                        url:'/api/articles/0'
                    })
                    .then(sendResponse);
                }

                function sendResponse(response){
                    console.log(data);
                    return response.data;
                }
            }

        })    
    

This code is kept in a separate file. However, when I try running it, I encounter an

Error: $injector:unpr Unknown Provider
issue. I've searched for solutions but haven't found any helpful ones so far. Any suggestions?

Answer №1

It seems that the IIFE is not being correctly utilized in this code snippet.

You should place () at the end of the file to execute the function properly.

(function(){

angular.module('newstalk')
    .factory('dataService',dataService);

function dataService(){
    return {
        getArticles : getArticles
    };

    function getAricles(){
        console.log("yolo");
        return $http({
            method:get,
            url:'/api/articles/0'
        })
        .then(sendResponse);
    }

    function sendResponse(response){
        console.log(data);
        return response.data;
    }
}

})()

Adding () at the end will allow the function to be executed as intended. Currently, the IIFE is not being executed.

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

Does IE 8 really not support the .length property?

When I tried to upload an image, Stackoverflow gave me this error message: Oops! Your question couldn't be submitted because: The code in your post isn't formatted correctly. Make sure to indent all code by 4 spaces using the code toolbar bu ...

Regular expression pattern for consistently capitalizing the phrases "CA" and "USA" in an address string

end_address = 'joe's home, 123 test avenue, los angeles, ca, usa 90210'; end_address = end_address.replace(/\w\S*/g, function(txt){return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();}); The outcome of this code will ...

Generating a customizable HTML table using a two-dimensional array

My goal is to develop a flashcard website that allows users to add, edit, and delete flashcards. Each flashcard consists of two sides - front and back. Currently, users can add words but are unable to edit or remove them. To illustrate, I have created an e ...

Develop a new IntermediateBaseModel class specifically designed for Sequelize

Currently, I am utilizing Sequelize as my data ORM. In my implementation, there exists a straightforward User Class. import { Model } from "sequelize"; class User extends BaseModel { } export default User; With this setup, I can easily interac ...

RequireJS is timing out while loading the runtime configuration

I keep encountering a load timeout error with my run-time configuration, specifically with common.js. Although I have set the waitseconds value to 0 for files loaded from common.js, the loadTimeout issue persists for common.js itself. index.html <scr ...

Loading Data Using AJAX with JSON on Button Press - Dealing with Array Problems

I am trying to understand how to specifically select JSON objects when a line item meets certain variable criteria that is passed when a button is clicked. Currently, I have it working but the output displays as [object],[object]. I suspect this is happeni ...

Data refresh is not triggered by the API request

Today I decided to experiment with axios.all by creating the script below. However, I encountered a small issue. The script successfully retrieves data from the API when executed, but there is something puzzling me. Despite utilizing the setInterval functi ...

Troubleshooting: Why isn't setMetadata working in NestJS from authGuards

When I call my decorators, I want to set metadata for logging purposes. Within my controller, the following decorators are used: @Post("somePath") @Permission("somePermission") @UseGuards(JwtAuthGuard) @HttpCode(200) @Grafana( ...

Adding Bootstrap popovers to dynamically created elements via JavaScript is not possible

My current project involves using JavaScript to dynamically generate an array of cards in HTML. Each card includes a button that, when clicked, should display a popover. However, I am encountering an issue where the popover is not appearing as expected. In ...

Transferring Data from Angular to Node using Express

I am facing an issue where my Node.js application is not receiving the file that I am trying to send. I am unsure of how to verify if the file is being sent and received in req. <form> <input type = "file" file-model="files" multiple/> < ...

Effectively handle multiple connections from nodejs to postgres using the pg library

I need to run a script that performs multiple queries using the pg library for managing connections. However, I am facing an issue where my program stops working when the connection pool is full and does not queue future queries. I have tried setting the p ...

Facing an issue with webpack-dev-server where it displays a blank screen

Hello! I am currently in the process of creating my first MERN stack application, using Webpack as the build tool. The main objective is to have Express serving the APIs for the app and webpack-dev-server handling the static content (from my static directo ...

Utilizing Fullcalendar with a JSON PHP page for event data

I've been struggling to integrate a PHP page hosted on a MySQL server that generates a JSON feed into the "eventSources" array of Fullcalendar in my Ionic application. The calendar is showing up, but the dates from the feed are not displaying. Despite ...

Change this multiple condition into an ng-class conditional syntax

Hey there, I could really use some assistance in converting this if-else statement with 'or' condition into a format that can be utilized in ng-class. So here's my current ng-class setup with the conditions, however, it seems to be giving m ...

The ASP.NET Core MVC controller encounters a null input parameter when called by an ajax request

Here is the scenario involving an ajax call: ... $("#testBtn").click(function (e) { e.preventDefault(); $.ajax({ url: "/profile/GuestList", data: {"keytype": "1"}, method: "POST&q ...

Passing data from an ajax request to multiple functions in Javascript: Best practices

Currently, I have a function named impactData which is making an ajax call to retrieve data from a CSV file that I created. Upon success, the retrieved data is passed to my generateImpactData function, which converts the CSV file into an array of objects. ...

Can inner function calls be mimicked?

Consider this scenario where a module is defined as follows: // utils.ts function innerFunction() { return 28; } function testing() { return innerFunction(); } export {testing} To write a unit test for the testing function and mock the return value ...

Organize my JavaScript code by implementing a function

I have repetitive javascript code that I would like to refactor into a function. Is there a way to streamline this process and make the code more efficient? The two functions I want to consolidate are: bright() $(VARIABLE).find('.info').fadeTo ...

Unlocking the secrets of extracting dimensions from imported SVG components in nextJS

I am facing an issue with importing an SVG file as a component and trying to obtain its dimensions, but it keeps returning null. Can someone provide me with advice on how to resolve this? PS. When I try using getBBox(), it throws an error. Here is the co ...

The jQuery formvalidator plugin for file validation isn't functioning as expected

I am attempting to validate the file type input using the formvalidator.net plugin, however, I am not seeing any errors. What could be wrong with the code below? It is functioning properly for other types of input. Here is an example of what I am trying: ...