Error: Functionality cannot be achieved

Looking for assistance in resolving this issue. Currently, I am attempting to register a new user and need to verify if the username already exists or not. Below is the factory code used for this purpose:

.factory('accountService', function($resource, sessionService) {
    var service = {};
    service.register = function(account, success, failure) {
        if (success (service.userExists(account))){
            failure();
        } else {
            var Account = $resource("/Test/rest/account/student");
            Account.save({}, account, success, failure);
        }            
    };

    service.userExists = function(account, success, failure) {
        var Account = $resource("/Test/rest/account");
        var data = Account.get({
                username : account.username,
                password : account.password
            }, function() {
                var accounts = data.username;
                if (accounts && accounts.length !== 0) {
                    service.data = data;
                    success(account);
                } else {
                    failure();
                }
            }, failure);
    };

    service.getuser = function() {
        return service.data;
    };

    return service;
})

Encountering an error message when trying to run the code:

TypeError: success is not a function

Below is the controller that utilizes this factory:

.controller(
            "RegisterController",
            function($scope, sessionService, $state, accountService) {
                $scope.register = function() {
                    accountService.register($scope.account, function(
                            returnedata) {
                        sessionService.login($scope.account).then(
                                function() {
                                    $state.go("home");
                                });
                    }, function() {
                        $scope.registererror = function() {
                        }
                    });
                };
            })

Answer №1

I believe the error lies in this particular line

service.userExists(account)

The method signature you are using is

service.userExists = function(account, success, failure)

Therefore, when you call it "success" will be undefined in this scenario and the following line within "service.userExists"

success(account)

will result in an error

Below is a revised example with changes made to prevent this error. It is important to differentiate between failure and user existence; for demonstration purposes, I have modified the returnData in "success" to true/false.

.factory('accountService', function($resource, sessionService) {
var service = {};
service.register = function(account, success, failure) {
  service.userExists(account), function(answer){
       if (answer){
           success();
       } else {
           var Account = $resource("/Test/rest/account/student");
           Account.save({}, account, success, failure);
       }
  }, failure);        
};

service.userExists = function(account, success, failure) {
    var Account = $resource("/Test/rest/account");
    var data = Account.get({
            username : account.username,
            password : account.password
        }, function() {
            var accounts = data.username;
            if (accounts && accounts.length !== 0) {
                service.data = data;
                success(true);
            } else {
                success(false);
            }
        }, failure);
};

service.getuser = function() {
    return service.data;
};

return service;

})

Answer №2

function checkUser(account, onSuccess, onError)

...

if (onSuccess(checkUser(account)))

Attempting to call a function with three parameters using only one.

Answer №3

 if (service.userExists(account)) {
  success(param);
} else {
  failure(); // Make sure to define this method!
  var Account = $resource("/Test/rest/account/student");
  Account.save({}, account, success, failure);
}

To ensure the proper functioning of the script, attention must be paid to what functions are being called:

var test1 = "hello";
console.log(test1); //-> prints "hello"

var test2 = function(){
  console.log("hello")
}
console.log(test2); //-> prints something like "function()....."
console.log(test2()); //-> prints "hello"

Answer №4

.factory(
            'accountService',
            function($resource, sessionService) {
                var service = {};
                service.register = function(account, success, failure) {
                    service
                            .validateUsername(
                                    account,
                                    function(result) {
                                        if (result) {
                                            console.log(result);
                                            failure();
                                        } else {
                                            var Account = $resource("/Test/rest/account/student");
                                            Account.save({}, account,
                                                    success, failure);
                                        }
                                    }, failure);
                };
                service.checkIfUserExists = function(account, success, failure) {
                    var Account = $resource("/Test/rest/account");
                    var data = Account.get({
                        username : account.username,
                        password : account.password
                    }, function() {
                        console.log("user details : ", data);
                        var accounts = data.username;
                        if (accounts && accounts.length !== 0) {
                            service.data = data;
                            success(account);
                        } else {
                            failure();
                        }
                    }, failure);
                };
                service.validateUsername = function(account, success, failure) {
                    var Account = $resource("/Test/rest/account/user");
                    var data = Account.get({
                        username : account.username
                    }, function() {
                        var accounts = data.username;
                        if (accounts && accounts.length !== 0) {
                            service.data = data;
                            success(true);
                        } else {
                            success(false);
                        }
                    }, failure);
                };
                service.getUserDetails = function() {
                    return service.data;
                };
                return service;
            })

and for the controller:

.controller(
            "RegisterController",
            function($scope, sessionService, $state, accountService) {
                $scope.register = function() {
                    accountService.register($scope.account, function(
                            returnedData) {
                        accountService.checkIfUserExists($scope.account, function(
                                account) {
                            sessionService.login($scope.account).then(
                                    function() {
                                        $state.go("get_started");
                                    });
                        });

                    }, function() {
                        $scope.registerError = function() {
                        }
                    });
                };
            });

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

The Karma Node Package is failing to run and providing no information

I've been troubleshooting an issue with my karma.conf.js file for the past two days. Despite my efforts, the terminal output provides no helpful information to identify the source of the problem. There are no hints within the document itself indicatin ...

Transform Firebase array into a text message

I'm looking to develop an application that displays text values from Firebase, but I'm unsure on how to implement this in my index file. Here is my index file: <!DOCTYPE html> <html ng-app="root"> <head> <script src="h ...

What is the best way to test chained function calls using sinon?

Here is the code I am currently testing: obj.getTimeSent().getTime(); In this snippet, obj.getTimeSent() returns a Date object, followed by calling the getTime() method on that Date. My attempt to stub this functionality looked like this: const timeStu ...

In what ways can you shut down an electron application using JavaScript?

My Electron app is running an express server. Here is the main.js code: const electron = require("electron"), app = electron.app, BrowserWindow = electron.BrowserWindow; let mainWindow; function createWindow () { ma ...

The Stripe payment form effortlessly updates in real-time thanks to the powerful @stripe/react-stripejs module

I am experiencing some difficulties with implementing Stripe payment in my Medusa-JS Next JS frontend. Whenever I enter card details in the checkoutForm, the entire StripePayment component keeps re-rendering every time I click on anything within the form ...

Using Conditions in a Javascript For Loop

I would like to utilize a for loop to achieve the following task. Within an array, I have a predefined set of values representing hex colors for a chart. My goal is to extract a specified number of those values using the loop with two options. If the ...

Unlimited Caching: A Guide to Storing HTTP Responses permanently

Is there a way to send an HTTP response that will be cached by any client indefinitely, so that the browser can retrieve it from the local file system without making any new HTTP requests when needed? Just imagine using this for versioned client code in a ...

Troubleshooting Safari's Issue with onclick() Functionality

I encountered an issue where the code was working perfectly on IE7 but not on Safari (5.0.5). I would like to find a solution without relying on jQuery. The ultimate goal is for this functionality to work seamlessly on iPad, but currently, I am testing it ...

Is Fetch executed before or after setState is executed?

I've encountered an issue while trying to send data from the frontend (using React) to the backend (Express) via an HTML form, and subsequently clearing the fields after submission. The code snippet below illustrates what I'm facing. In this scen ...

What is the method to access the controller value within a metadata tag?

One of the challenges I am facing is how to access a variable from a controller and use it in a metadata tag using AngularJS. Below is my approach: First, let's define the variable in the controller: app.controller('homeCtlr', function($sc ...

Issue: The code is throwing an error "TypeError: Cannot read property 'push' of undefined" in the JavaScript engine "Hermes

Can anyone assist me with filtering an array of objects in a TypeScript React Native project using state to store array values and filter objects in the array? Having trouble with the following error in the mentioned method: LOG after item LOG inside ...

rearranging the sequence of buttons using JavaScript

I am faced with the challenge of making a series of buttons draggable and droppable within a parent div without using any external libraries at the request of the client. Although I could have easily accomplished this task with jQuery, it's an opportu ...

Avoid the default behavior when employing jQuery for Ajax requests

I am facing an issue with preventing the default action when submitting a form using ajax. It seems that my code is causing a page refresh and clearing the form without sending any data to the database. I tried including the php processing script link in t ...

Discover the process of executing two functions simultaneously by interacting with a VRbutton through React360

As a newcomer to React, I am still learning the ropes and facing a challenge with using two functions simultaneously with Vrbutton (or any button) on onClick event. I have attempted various methods (referenced in my commented out code below) to make multi ...

Obtaining a byte array using the file input method

var profileImage = fileInputInByteArray; $.ajax({ url: 'abc.com/', type: 'POST', dataType: 'json', data: { // Other data ProfileImage: profileimage // Other data }, success: { } }) // Code in Web ...

Challenges Encountered with Random Image Generator in JavaScript

I am encountering an issue with a script that is supposed to change the default images to a random image each time the page is refreshed. However, I keep receiving an error stating that boxID is null. Why is boxID null? <script type="text/javascript" ...

Using Ruby instead of Javascript in lessc

My CSS is compiled in a node application using lessc. LESS was installed via NPM. When I check the current version of lessc --version it shows lessc 1.3.3 (LESS Compiler) [Ruby] 2.3.2 How can I change it to display lessc 1.3.0 (LESS Compiler) ...

How can I convert a string number with leading zeros into a string in a node.js environment?

When rendering a page, I pass the id as a string (e.g. 001, 002) but at the client side, I receive it as a number (e.g. 1, 2). res.render('leafletDemo',{id:userID,latitude:latitude,longitude:longitude}); Is there a way to keep the id as a str ...

Sending the image's identification number as a parameter to a function and showing the total number

On a static page, I have the following HTML markup: <div class="middle-content"> <div class="white-div"> <div class="like-buttons"> <img id="1" src="up.png" onclick="onClick(true, this.id)" /> &l ...

The onDrop event in javascript seems to be failing to execute

My attempts to get the javascript onDrop event to execute when an object is dropped into a drop zone have been unsuccessful. I've tried rewriting it in various ways without any success or error messages. In my search for potential reasons why the ondr ...