AngularJSError

I am completely new to AngularJS and I've been tasked with debugging someone else's code. While debugging in Google Chrome, I encountered the following error:

TypeError: accountService.logIn(...).success is not a function.

The issue lies within the signUp form on the line

accountService.logIn(signupform).success(function (response) {
. If more details are required, please do let me know. Below you will find my complete controller setup.

(function () {
'use strict';

angular
    .module('vidaexpress')
    .controller('accountController', accountController);

accountController.$inject = ['$rootScope', '$state', '$stateParams', 'accountService', 'facebookService', 'toastr'];

function accountController($rootScope, $state, $stateParams, accountService, facebookService, toastr) {
    var vm = this;
    vm.logIn = logIn;
    vm.signUp = signUp;
    vm.signOut = signOut;

    vm.facebookLogin = facebookLogin;
    vm.facebookLogout = facebookLogout;

    vm.recoveryPassword = recoveryPassword;
    vm.resetPassword = resetPassword;
    vm.sendVerifyEmail = sendVerifyEmail;

    function logIn(loginform) {
        vm.signinloading = true;
        accountService.logIn(loginform)
        .then(function (response) {
            if (response && response.error) {
                toastr.error(response.error);
            } else {
                accountService.setUserInfo(response);
                if (!$rootScope.returncust) {
                    window.sessionStorage.setItem('returncust', true);
                }
                vm.isAccountOpen = false;                   
            }
        }, function (error) {
            toastr.error(error.error);
        }).finally(function () {
            vm.signinloading = false;
        });
    }
    function signUp(signupform) {
        vm.signuploading = true;
        accountService.signUp(signupform)
        .then(function (response) {
            if (response && response.error) {
                toastr.error(response.error);
            } else {
                accountService.logIn(signupform).success(function (response) {
                    accountService.setUserInfo(response);
                    logIn();
                }).error(function(error) {
                    toastr.error(error.error);
                });
            }
        },function (error) {
            toastr.error('System Error');
        }).finally(function () {
            vm.signuploading = false;
        });
    }
    function signOut() {
        //Log out API
        //accountService.logOut();
        //Log out Facebook
        var userInfo = accountService.getUserInfo();
        if (userInfo.facebookLogin) {
            facebookLogout();
        }
        //Log out UI
        accountService.setUserInfo(null);
        vm.isAccountOpen = false;
        $state.go('main.index');
    }
    function facebookLogin() {
        facebookService.login();
    }
    function facebookLogout() {
        facebookService.logout();
    }
    function recoveryPassword(email) {
        accountService.recoveryPassword(email).then(function (response) {
            if (response && response.error) {
                toastr.error(response.error);
            } else {
                toastr.success('An email has been sent.');
            }
        }, function () {
            toastr.error('System Error');
        });
    }
    function resetPassword(model) {
        model.customerId = $stateParams.id;
        model.token = $stateParams.token;
        accountService.resetPassword(model).then(function (response) {
            if (response && response.error) {
                toastr.error(response.error);
            } else {
                toastr.success('Your password has been reset.');
            }
        }, function () {
            toastr.error('System Error');
        });
    }
    function sendVerifyEmail() {
        accountService.sendVerifyEmail().then(function (response) {
            if (response && response.error) {
                toastr.error(response.error);
            } else {
                toastr.success('Email has sent');
            }
        }, function () {
            toastr.error('System Error');
        });
    }
}
})();

Below is the content of my account.server.js file for reference.

(function () {
'use strict';

angular
    .module('vidaexpress')
    .service('accountService', accountService);

accountService.$inject = ['$http', '$window', '$rootScope', 'apiUrl'];

function accountService($http, $window, $rootScope, apiUrl) {
    var baseUrl = apiUrl.account;
    var cookieUser;
    var sessionName = 'userInfo';

    this.logIn = logIn;
    this.logOut = logout;
    this.signUp = signUp;
    this.setUserInfo = setUserInfo;
    this.getUserInfo = getUserInfo;
    this.confirm = confirm;
    this.recoveryPassword = recoveryPassword;
    this.resetPassword = resetPassword;
    this.sendVerifyEmail = sendVerifyEmail;

    function logIn(credential) {
        return $http({
            method: 'POST',
            url: baseUrl + 'token',
            headers:{ 'Content-Type': 'application/x-www-form-urlencoded' },
            transformRequest: function (obj) {
                var str = [];
                for (var p in obj)
                    str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p]));
                return str.join("&");
            },
            data: {
                grant_type: 'password',
                email: credential.email,
                password: credential.password
            }
        }).then(function (response) {
            if (!response) {
                return { error: 'System Error' };
            } else if (response.error) {
                return { error: response.error };
            } else {
                return response.data;
            }
        }, function (error) {
            return { error: 'System Error' };
        });
    }
    function logout() {
        return $http.post(baseUrl + 'logout');
    }
    function signUp(userInfo) {
        return $http.post(baseUrl + 'signup', userInfo);
    }
    function setUserInfo(userInfo) {
        cookieUser = userInfo;
        $rootScope.currentUser = userInfo;
        $window.sessionStorage.setItem(sessionName, JSON.stringify(userInfo));
    }
    function getUserInfo() {
        if (!cookieUser) {
            cookieUser = JSON.parse($window.sessionStorage.getItem(sessionName));
        }
        return cookieUser;
    }
    function confirm(customerId, token) {
        $http.get(baseUrl + 'verifyEmail?id=' + customerId + '&token=' + token);
    }
    function recoveryPassword(email) {
        return $http.get(baseUrl + 'recoveryPassword?email=' + email).then(function (response) {
            return null;
        }, function () {
            return { error: 'System Error.' };
        });
    }
    function resetPassword(model) {
        return $http.post(baseUrl + 'resetPassword', model).then(function () {
            return null;
        }, function(){
            return { error: 'System Error' };
        });
    }
    function sendVerifyEmail() {
        return $http.get(baseUrl + 'sendVerifyEmail').then(function (response) {
            return null;
        }, function () {
            return { error: 'System Error.' };
        });
    }
}
})();

Answer №1

Your controller needs to adopt .then() instead of success() for the return pattern in the service to function properly.

userService.signIn(loginform)
    .then(function (response) {

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

Improvement in Select2 Change Event: Update the subsequent select2 box options based on the value change in the preceding select2 box

I need assistance with two select boxes, namely Category and Sub-category. My objective is to dynamically alter the available options in the subcategory box based upon the value selected in the category box. Additionally, I would like to load data for the ...

Share the name of the Quasar component with the Vue 3 render function

I'm struggling to dynamically create a Vue 3 app with different components specified by name, such as "div", "button", or Quasar's "q-btn". When I try to pass the latter to Vue's render function Vue.h, I encounter difficulties. <html> ...

Discover the key steps to extracting codes within a string in React or Javascript

I am currently developing an application that could potentially receive a string from the backend server. The string might look something like this: If you were to fold a piece of paper in half 50 times, its width would be three-quarters of the distance fr ...

Tips for testing an Angular factory function

I am attempting to run a test on a factory using protractor and angular.mocks Below is the code for the factory: angular.module('googlemarker', []) .factory('newMarker', newMarkerFactory); newMarkerFactory.$inject = ['$windo ...

Switching the border of a div that holds a radio button upon being selected

I have a piece of code that I use to select a radio button when clicking anywhere within a div, which represents a product photo. To make it clear for the customer, I want to add a border around the selected product. Here is the initial code: <script t ...

I'm having trouble managing state properly in Safari because of issues with the useState hook

Encountering Safari compatibility issues when updating a component's state. Though aware of Safari's stricter mode compared to Chrome, the bug persists. The problem arises with the inputs: Whenever an option is selected from the dropdown, it cl ...

Encountering a Null Pointer Exception when trying to locate an element on an AngularJS website using Selenium

Testing an AngularJS website with Selenium can be challenging due to angular directives, as mentioned in a blog. Despite encountering some stability issues such as failures and exceptions like "unable to locate Element," "No such element," or "Null pointer ...

I'm trying to implement a command in my bot that displays the number of Discord members, but I keep encountering an error

I've encountered an issue with the discord.js v13 member count command. Despite seeking help in various Discord servers, I haven't received any assistance. If anyone could offer their expertise, it would be greatly appreciated. const Discord = re ...

Using the IE method getelementbyid to target an object within the document

Is there a way to use getElementById to access an object that already exists in the document? I am specifically trying to target the element "test" which is nested within parentDiv1. While this code works in Firefox, it's not functioning properly ...

What is the best way to determine the actual height of a DOM element that is being hidden by the overflow property in order to create a seamless CSS transition to height: auto

Solution: Thanks to @Kalimah, here's a solution that works in composition api & script setup: <script setup> const state = reactive({ meetCardHeight: 100 }) const element = ref(null) const changeElementHeight = () => { if (stat ...

Shattered raw emotion

Does anyone have any insight on how to resolve this error? I've hit a roadblock trying to figure out the issue in the message below. Here is the snippet of code: :label="` ${$t('cadastros.clientes.edit.status')}: ${cliente.status === ...

Extracting data from the response object and injecting it into the request

Once the file has been successfully uploaded, the 'uploadSuccess' callback event is triggered, providing information about the newly created media. The 'hashed_id' value within this object is crucial for my PUT request. I attempted to ...

Implementing autocompletion in an ASP.NET MVC4 application with AJAX and jQuery

I have been attempting to implement an autocomplete feature in a textbox that fetches company names. Despite successfully retrieving records and receiving them in the success function via Ajax, I am not seeing any suggested autocompletions in the textbox. ...

transfer a product attribute value to a different product attribute within the Magento platform

There is an attribute called Weight : Attribute Code: weight Scope: general Catalog Input Type for Store Owner: Text Field Values Required: yes Apply To: Simple Product, Bundle Product Allow HTML Tags on Frontend: yes Also, there is a General Weight attr ...

The data visualization tool Highchart is struggling to load

As I try to integrate highcharts into my website, I encounter an unexpected error stating TypeError: $(...).highcharts is not a function. Below is the code snippet in question: @scripts = {<script src="@routes.Assets.at("javascripts/tracknplan.js")" ty ...

Directing a controller assignment in AngularJS 1.2 via a directive

Transitioning from angularJS 1.0 to 1.2 has presented a challenge for me when it comes to assigning a controller to a directive with a distinct scope, without explicitly defining the controller in my HTML using ng-controller. Let's look at this scena ...

Utilizing document.write() for displaying markup content

I have an inline SVG stored as a variable on my webpage and I am making some changes to it. How can I display viewText on the page (not the SVG image) with the modifications? What is the best way to make viewText appear on the page? For instance: ...

Troubleshooting the malfunctioning AngularJS ui-view component

My ui-view isn't functioning properly, but no errors are being displayed. Can anyone help me figure out what I'm missing to make this work? This is the main template, index.html. <!DOCTYPE html> <html> <head> <meta charset= ...

Tips on sending asynchronous requests to a PHP page using jQuery AJAX

As a newcomer to web development, I am working on creating a social networking website for a college project. One feature I want to implement is updating the message count in the menu every time there is a new message in the database for the user (similar ...

I am looking for solutions to decrease the size of my AngularJS bundle when using Webpack. Can anyone provide

I've been working on developing an AngularJS app (v1.7.x) and I'm facing a challenge with the large production file size. The original dependency in node_module is 1.30 MB and 170 kB (minified). After adding just a basic console.log, the build f ...