Bizarre error when injecting Factory into Controller in AngularJS

After scouring through countless posts on various forums, I have yet to find a solution to my unique problem. I find myself in a peculiar situation where I am trying to inject a Factory into a Controller, and despite everything appearing to be in order, it just doesn't seem to work as expected.

Below is the factory code snippet:

zimmerApp.factory('AuthService', [function ($http, $sanitize) {
var sanitizeCredentials = function (credentials) {
    return {
        email: $sanitize(credentials.email),
        password: $sanitize(credentials.password),
        csrf_token: credentials.csrf_token
    };
};
return {
    login: function (credentials) {
        var login = $http.post("/login", sanitizeCredentials(credentials));
        login.success(cacheSession);
        login.error(loginError);
        return login;
    }
};
}]);

And here is the controller where I intend to use AuthService:

zimmerApp.controller('loginCtrl', ['$scope', 'AuthService',
    function ($scope, $location, AuthService) {
    var xhReq = new XMLHttpRequest();
    xhReq.open("GET", "http://" + window.location.hostname + ":8000/auth/token", false);
    xhReq.send(null);

    $scope.error = false;
    $scope.credentials = {
        username: '',
        password: '',
        csrf_token: xhReq.responseText
    };

    $scope.login = function (credentials) {
        AuthService.login($scope.credentials)
            .success(function () {
                $location.path('/');
            })
            .error(function (err) {
                console.log('error');
            });
    }
}]);

The error message that keeps popping up reads:

TypeError: Cannot read property 'login' of undefined

It appears that the AuthService factory is not being recognized for some reason. If anyone has any insight on how to resolve this issue, I would greatly appreciate the guidance as I feel like I've tried everything at this point.

Answer №1

The parameters being passed in do not match the parameters expected in your function.

Update to:

 zimmerApp.controller('loginCtrl',
     ['$scope', 'AuthService',
      function ($scope, $location, AuthService) {

Change it to:

zimmerApp.controller('loginCtrl',
    ['$scope', $location, 'AuthService',
    function ($scope, $location, AuthService) {

I personally prefer not using the inject array method:

zimmerApp.controller('loginCtrl',
    function ($scope, $location, AuthService) {

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

Converting data into a multidimensional array in AngularJS: A comprehensive guide

Struggling to convert a JSON array into a multidimensional array, looking for some guidance. I attempted using _.groupBy in underscore.js, but it's not proving successful with the nested array. If there is any way to convert from the given data [{ ...

utilize the useRef hook to display the total number of characters within a text area

Introducing the following component: import React from 'react'; export interface TexareaProps extends React.TextareaHTMLAttributes<HTMLTextAreaElement> { maxLength?: number; id: string; } export const Textarea = React.forwardRef( ( ...

Leveraging next-generation JavaScript (NextJS), incorporate sass-loader for seamless inclusion of variables in each individual

I'm having trouble implementing a custom webpack configuration in my nextjs project. My objective is to automatically import @import "src/styles/variables.scss"; for all scss files in my application. I have successfully set up a webpack con ...

The error states that the type '() => string | JSX.Element' cannot be assigned to the type 'FC<{}>'

Can someone help me with this error I'm encountering? I am fairly new to typescript, so I assume it has something to do with that. Below is the code snippet in question: Any guidance would be greatly appreciated. const Pizzas: React.FC = () => { ...

Retrieving the chosen item from an ng-repeat list within a datalist

Currently, I am utilizing array iteration to identify the selected option based on the ID attribute of the result. Is there a more efficient approach for this task? <input type="text" list="products" ng-model="query" /> <datalist id="products"&g ...

Is it possible to eliminate the css class prefix when using Modular css in React?

When working with React & NextJS, I have observed that my modular SCSS files are automatically prefixing my classnames with the name of the file. Is there a way to turn off this feature as it is making the DOM structure difficult to interpret? For instanc ...

Utilize Angular JS to dynamically load a personalized directive that aligns with the scope of the

I am looking to create a reusable tabbed element that can dynamically load custom directives based on the active tab. Essentially, I want a directive within a directive. So far, I have successfully implemented the tab wrapper and functionality to update $ ...

When using React-hook-form, you need to tap twice to delete the last character in the input field, and double tap to enter the first

I have been using React Hook Form to validate my form with multiple inputs. Everything works perfectly, except I noticed one issue where I have to press the backspace key twice to delete the last character and also twice to enter the first character. For e ...

What strategies can I use to reduce the amount of event listeners assigned to buttons in jquery?

Currently, I am utilizing jquery 1.6.2 for my project. On one of the pages, I have a structure that resembles the following: <div id="section1"> <fieldset> <ul> <li> <input type="radio" name ...

Manipulating the actual DOM in ReactJS to display a formatted number or string while preserving its original value

Hello, I am new to ReactJS and currently using it along with ReactDataGrid. I am trying to figure out how to change the real DOM value of a specific cell in the table. Here is the table I am working with: https://i.sstatic.net/CAcSH.png My goal is to cha ...

I'm having some trouble with my jQuery.get() function in the javascript Saturday(), can anyone help me figure out what I'm doing wrong?

Can anyone help me troubleshoot my jQuery.get() method in the saturday() JavaScript function? Here is the code snippet I have been working on. This is what I have in my index.html file: <html> <head> <title>jVectorMap demo</title> ...

What is the purpose of utilizing these three JavaScript function parameters?

I've been researching JavaScript functions and arguments, but I haven't found anything that fully explains a function like the one below. For reference, you can check out the original tutorial. In createPuppy, there are three arguments: req, res ...

Counting JSON Models in SAP UI5

I am encountering a particular issue. Please forgive my imperfect English. My goal is to read a JSON file and count the number of persons listed within it. I want this result to be stored in a variable that is linked to the TileContainer. This way, whenev ...

Unable to access Form element in Firefox browser

I'm struggling with debugging unfamiliar problems. For instance, in my HTML there's a form: <form name="myForm" > <table> <tr> <td> <input type="radio" name="myType" value="val" onclick="someF ...

Tips for preventing CORS errors while rendering an image on a canvas

Working on a project for my coding bootcamp where I need to overlay bandaids on an image of a bear using canvas. The main challenge is to check the color of the area that users click to ensure they don't put bandaids on the white space around the actu ...

Utilizing Angular and Express for routing with the seamless integration of html5mode

I'm facing an issue with making angular and express routing work together with html5mode enabled. When I change state from '/' to my admins state, everything works fine until I refresh the page. Then I only get a json result of admins but my ...

Create a unique key dynamically based on a specified scope value using AngularJs

I am working with an angular directive that utilizes a title with a key from a messages.properties file. To dynamically generate the key, I want to concatenate 'root.' + scope.value + '.title' like so: titre="{{ 'flux.' + &ap ...

Mastering the art of utilizing callbacks in AngularJS for consuming an API

Having trouble handling data from an API and structuring it effectively before passing it to the controller. I've created a factory that retrieves user data from the API, but the provideAllUserData function is causing issues. Below is my services.js: ...

ReactJS tables that can be filtered and sorted

Within my component's state, there exists an array named 'contributors'. Each element within this array is an object containing various properties. My goal is to present this data in a table format, with the added functionality of sorting an ...

Is there a way to activate an event when using # or @ in a text field on React/Next.js?

I'm in the process of starting a new project and I am thinking about how to incorporate this into react/nextjs. I want to create a user selection or hashtag selection dialog around the textarea, but I haven't been able to find any helpful article ...