Angular - Uncaught TypeError: XX is not a function on the site

Seems like I might be overlooking a property somewhere, but as I'm following this project, I encountered this error in my controller.

TypeError: loginService.signin is not a function

This is the content of my controller.js file

angular.module('appcontrollers', []).controller('LoginController', ['$rootScope', '$scope', '$http', '$location', '$localStorage', 'loginService',  
        function ($rootScope, $scope, $http, loginService) {

        $scope.signin = function() {

            console.log("username: " + $scope.username);
            console.log("pass: " + $scope.password);

            var formData = {
                username: $scope.username,
                password: $scope.password
            };

            // ERROR AT THIS LINE
            loginService.signin(formData, function(res) {
                console.log("asdf");
                if (res.type == false) {
                    console.log(res.data);
                } else {
                    $localStorage.token = res.data.token;
                    console.log("Window location /");
                }
            }, function() {
                $rootScope.error = "Error en el logueo del usuario";
            });

            // Setting Token:
            $scope.token = $localStorage.token;
        }

    }])

This is the content of my service.js file

'use strict';

angular.module('app-services', [])
.factory('loginService', ['$http', '$localStorage', function ($http, $localStorage) {
    console.log('services - loginService');

    var baseUrl = "http://angular-restful-auth.herokuapp.com";

    function changeUser(user) {
        console.log('1');
        angular.extend(currentUser, user);
    }

    function urlBase64Decode(str) {
        console.log('2');
        var output = str.replace('-', '+').replace('_', '/');
        switch (output.length % 4) {
            case 0:
                break;
            case 2:
                output += '==';
                break;
            case 3:
                output += '=';
                break;
            default:
                throw 'Illegal base64url string!';
        }
        return window.atob(output);
    }

    function getUserFromToken() {
        console.log('3');
        var token = $localStorage.token;
        var user = {};
        if (typeof token !== 'undefined') {
            var encoded = token.split('.')[1];
            user = JSON.parse(urlBase64Decode(encoded));
        }
        return user;
    }

    // Set user token.
    var currentUser = getUserFromToken();

    return {
        save: function(data, success, error) {
            $http.post(baseUrl + '/signin', data).success(success).error(error)
        },
        signin: function(data, success, error) {
            $http.post(baseUrl + '/authenticate', data).success(success).error(error)
        },
        me: function(success, error) {
            $http.get(baseUrl + '/me').success(success).error(error)
        },
        logout: function(success) {
            changeUser({});
            delete $localStorage.token;
            success();
        }
    };
}

]);

Everything seems to be working fine until the user clicks on the submit button triggering the signin() function. The console logs the correct data as:

>> username: somename
>> pass: somepassword

However, immediately after that, an error arises. Any guidance or assistance on how to resolve the issue with passing the signin() function would be greatly appreciated.

Answer №1

It is important to maintain the correct order of dependencies when using Dependency Injection arrays in your functions.

Sample Code

angular.module('appcontrollers', []).controller('LoginController', ['$rootScope', '$scope', '$http', '$location', '$localStorage', 'loginService',  
        function ($rootScope, $scope, $http, $location, $localStorage, loginService) {

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

Here's the step-by-step process: Access the specific item in the object by referencing `obj[i]["name of desired attribute"]

I tried seeking advice and consulting multiple sources but none provided a suitable answer. Is there someone out there who can assist me? obj[i].["name of thing in object"] Here's the array: [ { "name": "DISBOARD#2760" ...

Is it possible to utilize PropTypes to indicate that a prop is of type Promise?

Using PropTypes can aid in debugging by providing warnings when expectations are not met. Additionally, they serve as a helpful tool to clearly express how a component should be used. If I have a component that requires a prop with a value that could pote ...

When using window.location.href and location.reload(), the updated page content from the server is not loaded properly

Currently, I am working on a form that is being updated via an AJAX call. Once the AJAX call successfully completes, I want to reload the page in order to display the new changes. Even though I tried using location.reload() and window.location.href after ...

Encountering an error when attempting to access an object property dynamically by using a passed down prop as a variable in Vue 2 & Vuex

I have been struggling for hours to find a solution to this problem, but so far I've had no luck. I've looked at these two questions, but they didn't provide the answers I needed: Dynamically access object property using variable Dynamical ...

Using Javascript to retrieve information from a json file

I am currently working on incorporating JSON data into my script. I have noticed that when I manually declare a variable and check the console output, everything seems to work fine. <script> data = '[{"id": 1,"name": "Germany"},{"id": 2,"name": ...

Blueprint for Multi-User Application with Mongoose Schema

I am in the process of designing a schema for a multi-user application that will be developed using MongoDB, Express, AngularJS, and NodeJS. This application will cater to four different types of users: GUEST, REGISTERED_USER, SUBSCRIBER, and ADMIN. Once a ...

Validation with Javascript can trigger the display of a hidden element

Hello there, I could really use some assistance with the JavaScript part of this code. I have two JavaScript functions: one for validating if a radio checkbox is selected, and another for revealing the "answer". Currently, an alert pops up if no selections ...

Why is the observable I'm utilizing in this Angular 11 component returning as undefined?

Currently, I am working on implementing a promotions feature for an Angular 11 e-commerce application. I have developed a service that sends a get request and retrieves a JSON file containing the campaign's information. The Service: import { Injectab ...

The function DataTable is not defined in jQuery(...)

When attempting to use jQuery DataTable with Angular JS in my ServiceNow application, I encountered the error message jQuery(...).DataTable is not a function. To resolve this issue, I created a variable 'j' to prevent conflicts between jQuery and ...

How to establish a session in CodeIgniter with the help of JavaScript

Currently, I am trying to save the session in jQuery. Specifically, I am attempting to store all the IDs that are checked via checkboxes in the export_type variable and then save them in the session. However, when running the following code snippet, I en ...

Can someone please guide me on how to display a modal on top of another in AngularJS?

Currently, I am troubleshooting a coding issue. Due to the integration of a loader on my website, there is a clash with the modals. As a solution, I have been opening the modal from my controller. However, I am facing an issue where the newly opened moda ...

AngularJS provides several ways to redirect users to different views within a

Although it may seem simple, I am new to angularjs. Here is the code for my angularjs controller: function MyCtrl1($scope, $location, $rootScope) { $scope.$on('$locationChangeStart', function (event, next, current) { event.preventDefau ...

Can the localization be embedded into an svg image?

I am currently engaged in a project that involves working with multiple languages in React using i18next. Within this project, I have a set of SVG images that contain fixed text in a specific language. Here is a snippet from one of the SVG images: <tex ...

Create a PHP form that includes text and image inputs with the help of AdminLTE and integrates DropZone.js

I have been working with a template from adminLTE and you can check it out at the following link: . At this point, I am trying to upload images first and then use the image names as input text elements in my main form for submission. However, I have encou ...

Vue's smooth scrolling in Nuxt.js was not defined due to an error with the Window

There seems to be an issue with adding vue smooth scroll to my nuxt.js project as I'm encountering the "window is not defined error". The steps I followed were: yarn add vue2-smooth-scroll Within the vue file, I included: import Vue from 'vue ...

Struggling to extract specific data from a table using angular.js

My table includes Roman numerals (i.e. I, II, III, ......VIII) for filtering using Angular.js. However, I am facing an issue where the filtration process works for some values but not for others. Please review my code below: subject.html: <table cl ...

Attempting to utilize the async/await method to retrieve a service, but unfortunately, the returned values from the second service are not populating my variables as intended

I am having an issue with my service where I retrieve a list from the server. The problem is that within this list, I need to make another service call to fetch logo images. Although the service call returns successfully, my list still remains empty. Can y ...

javascript: restrict the quantity of products

As a beginner in javascript, I am currently working on creating a simple RSS reader. However, I am facing a challenge in limiting the number of feeds to 5 items, especially since the target site may have 100 or more feeds. Here's the code snippet I&ap ...

how can JavaScript be used to retrieve an object based on a condition from an array of objects and an ArrayList

My JavaScript challenge involves working with an array of objects called arrobj and a list called prgList. The goal is to extract the names from arrobj based on the programs listed in prgList. If the program exists in arrobj, it should be displayed accor ...

Generate an array that can be accessed across all components

As someone new to reactjs, I'm trying to figure out how to handle an array of objects so that it can be global and accessed from multiple components. Should I create another class and import it for this purpose? In Angular, I would typically create a ...