Error: Unable to access Main.login function

Currently integrating this example into my project. You can access the front-end code here.

Displaying my controller below:

(function(){
'use strict';
/* authentication Controllers */

var app = angular.module('pook');
    app.controller('authCtrl',['$http','$rootScope', '$scope', '$location', '$localStorage', 'ngToast', 'Main', function($http, $scope, $location, $localStorage, ngToast, Main){
        $scope.login = function(){
            var formData = {
                username: $scope.username,
                password: $scope.password
            };
      Main.login(formData, function(res) {
          if (res.type == false) {
              alert(res.data)    
          } else {
              $localStorage.token = res.data.token;
              window.location = "/";    
          }
      }, function() {
          $rootScope.error = 'Failed to signin';
      });
        }
    }]);
})();

My factory service is shown below:

(function(){
    'use strict';
    var app = angular.module('pook')
        app.factory('Main', ['$http', '$localStorage', function($http, $localStorage){
            var baseUrl = "127.0.0.1:3000/api";
            function changeUser(user) {
                angular.extend(currentUser, user);
            }

            function urlBase64Decode(str) {
                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() {
                var token = $localStorage.token;
                var user = {};
                if (typeof token !== 'undefined') {
                    var encoded = token.split('.')[1];
                    user = JSON.parse(urlBase64Decode(encoded));
                }
                return user;
            }

            var currentUser = getUserFromToken();

            return {
                save: function(data, success, error) {
                    $http.post(baseUrl + '/users', data).success(success).error(error)
                },
                login: function(data, success, error) {
                    $http.post(baseUrl + '/login', 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();
                }
            };
        }
    ]);
})();

Through a direct copy-paste from the example, with only the app and controller name changed, I am encountering the following error:

TypeError: Main.login is not a function
    at Scope.$scope.login (http://127.0.0.1:3000/js/controllers/auth.js:15:12)
    at $parseFunctionCall (https://ajax.googleapis.com/ajax/libs/angularjs/1.3.15/angular.js:12404:18)
    at ngEventDirectives.(anonymous function).compile.element.on.callback (https://ajax.googleapis.com/ajax/libs/angularjs/1.3.15/angular.js:21566:17)
    at Scope.$get.Scope.$eval (https://ajax.googleapis.com/ajax/libs/angularjs/1.3.15/angular.js:14466:28)
    at Scope.$get.Scope.$apply (https://ajax.googleapis.com/ajax/libs/angularjs/1.3.15/angular.js:14565:23)
    at HTMLFormElement.<anonymous> (https://ajax.googleapis.com/ajax/libs/angularjs/1.3.15/angular.js:21571:23)
    at HTMLFormElement.jQuery.event.dispatch (https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.js:4435:9)
    at HTMLFormElement.jQuery.event.add.elemData.handle (https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.js:4121:28)

Despite the presence of the Main.login function, the error suggests otherwise. I am puzzled by this.

Answer №1

It seems that the issue here is related to the misconception about the Main variable. When utilizing explicit dependency injection annotations, it is crucial to ensure that the order and number of dependencies and injected arguments are aligned.

.controller('authCtrl',
     ['$http','$rootScope', '$scope', '$location', '$localStorage', 'ngToast', 'Main', 
                ^^^____
    function($http, $scope, $location, $localStorage, ngToast, Main)

Upon examination, it appears that an additional rootScope dependency has been injected into the variable scope, causing a shift in the order of arguments. As a result, the Main variable actually ends up holding the $location object. It is recommended to carefully review the argument list and utilize console logging for verification. Additionally, maintaining proper indentation can help manage situations with numerous injected arguments.

By removing $rootScope from the injection list, the issue should be resolved.

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

Identifying the device name in Safari on iOS 13 despite the inaccurate display of the user agent - a step-by-step guide

Following the release of Apple's iOS 13, I discovered that window.navigator.userAgent in Safari on iPad iOS 13 is identical to that on MacOS. It appears like this: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15) AppleWebKit/605.1.15 (KHTML, like Gecko) ...

Accessing configuration properties from a JavaScript file in AngularJS version 1.5.X

Looking to retrieve configuration values based on environment. The config.js file contains the following entries: config.js: baseUrl='/home', abcUrl='/abc' I am attempting to access the baseUrl and abcUrl within one of my services us ...

Customize Nivo LightBox to apply to only one video separately on the page

I've recently implemented the Nivo LightBox script on my website for a video popup effect. However, as a newcomer to jQuery, I'm struggling to customize the lightbox to only trigger when clicking a specific link for my video, rather than every li ...

Instructions on inserting a new row beneath a selected row using jQuery

https://i.stack.imgur.com/AlwHm.png When the second column is clicked, the method below is called: function getListOfList(primaryId, isFlat, col) { alert(primaryId) $.ajax({ url : ("/" + serverURL + "/dataGrid/getChilds"), ...

Setting the default selection in AngularJS based on the URL entered

I've encountered an issue with a dropdown menu in my AngularJS version 1.4 application. The dropdown menu contains links to different sections of the page. The problem arises when I directly enter the page URL - instead of selecting the correct link f ...

The scope of this variable in Node.js results in an undefined response

Have you ever noticed the difference in behavior when executing JavaScript code in Google Chrome's console compared to running the same logic in a file using Node.js? function foo() { console.log( this.bar ); } var bar = "global"; foo(); In Chr ...

The jQuery prop method seems to be malfunctioning

Here is the HTML code snippet: <ul class="expander-list" id="category"> <li> <div class="radio" style="padding-left:0px"> <label> <input type="checkbox" id="all" ...

What is the best approach to incorporating Ant-design-vue via cdn in my project?

I've been working on a Vue macro application for specific functionality in NetSuite. Since I can't utilize npm or other package installers, I've resorted to using CDN. The Vue app and Ant Design are both functioning properly, but the issue l ...

Utilize Meteor-tabular to effortlessly export data with convenient HTML5 export buttons

Currently, I am utilizing the tabular package to display data from a collection in a table format. However, when attempting to export the data using html5 export buttons with the button (csvhtml5), only the length of data visible in the table is exported, ...

What is the best way to continuously run a series of setInterval() functions in a never-ending

I attempted to create a function that would post measurement A every 5 seconds for 10 times, followed by posting measurement B at random intervals. The goal was to have this function repeat indefinitely in order to simulate a fake agent. My initial code l ...

The redirection to the HTML page happens too soon, causing the ASYNC functions to fail in saving the user's image and data to the server

Hey everyone! I'm facing an issue with async/await functions. Here's the code snippet from my backend where I'm trying to save details of a newly registered user. I'm puzzled as to why the Redirect() function is executing before the f ...

Issue with Angular Material date picker

While attempting to implement the md-datepicker component, I encountered some errors in the console. My HTML Code: <md-datepicker ng-model="vm.addfamilymember.dob" md-placeholder="Date of Birth"> </md-datepicker> Error Messag ...

Ways to host static content in ExpressJS for specific directories and exclude others

I need to configure my ExpressJS server to serve static files from specific paths only, excluding others. For example, I want to serve static files from all paths except /files where I only need to manipulate a file on the server. Currently, my code looks ...

unable to establish connection due to port error in node.js

While executing node app.js I encountered the following error message info - socket.io started warn - error raised: Error: listen EACCES This snippet shows all the JavaScript code within the application. After running sudo supervisor app.js T ...

An effective method for retrieving textarea data in Node.js

I am facing an issue where I cannot successfully send data from a <textarea> to Node.js. It seems that the data I'm trying to send is not being received by Node.js. To retrieve data in Node.js: continueBtn.addEventListener("click", ...

What is the best way to retrieve the session identifier when utilizing Socket.IO?

I am in need of managing unique connections for my chat application. After doing some research, I realized that all the solutions I came across are outdated. Therefore, I am wondering how I can retrieve a socket's session ID using Socket.IO. The tec ...

What are the steps to ensure the effective functioning of my checkbox filter?

Currently, my product list is dynamically created using jQuery. I now need to implement filtering based on attributes such as color, size, and price. I found some code that filters the list items by their classes, which worked perfectly for someone else. ...

Sending a directive as an argument to a parent directive function

edit: I made adjustments to the code based on stevuu's recommendation and included a plunkr link here Currently, my goal is to make a child directive invoke a method (resolve) through another directive all the way up to a parent directive. However, I ...

Navigating the Basics: Understanding the Four Quadrant Selection Grid in a Material UI & React Pop-Up Form

Sorry if these questions seem silly. I'm diving into React & Material-UI without a mentor to guide me, relying on documentation and tutorials. Is there a better place for quick beginner questions? Maybe a chat forum or Slack group? Not sure if Stack i ...

Azure-Graph is reporting an error: 'Invalid or missing Access Token.'

In my Node.js project, I effortlessly integrate azure APIs. Logging in: const MsRest = require('ms-rest-azure'); MsRest.loginWithServicePrincipalSecret(keys.appId, keys.pass, keys.tenantId); Creating a resource group: const { ResourceManageme ...