Error: The function Users.create is undefined

After my code was initially running smoothly, I decided to add some new functions for login which unfortunately caused it to break. Even after removing the added code, the error message "create function of the user service is not a function" persists. Despite scouring through various sources for solutions, none of the suggested answers seem to resolve the issue.

UserController

todoApp.controller('UserController', ['Users','$scope', function UserController(Users, $scope) {
        console.log("in user controller");

        $scope.formModel = {};
        $scope.submitting = false;
        $scope.submitted = false;
        $scope.has_error = false;

        console.log($scope.formModel);
        $scope.createUser = function() {
            if(!$scope.registerForm.$valid) {
                return;
            }
            Users.create($scope.formModel)
            .success(function(data){

                $scope.submitting = false;
                $scope.submitted = true;
                $scope.has_error = false;
                $scope.formModel = {}; // clear the form so our user is ready to enter another
                $scope.users.push(data);
                console.log(":)");
            }).error(function(data) {
                console.log(":(");
                $scope.submitting = false;
                $scope.submitted = false;
                $scope.has_error = true;
            });


        };

    }]);
    

user.sevice.js

todoApp.factory('Users', ['$http', function($http) {
        return {
            get: function() {
                return $http.get('/api/users');
            },

            create: function(userData) {
                console.log(userData);
                return $http.post('/api/users', userData);
            },

            delete: function(id) {
                return $http.delete('/api/users/' + id);
            },

            update: function(userData) {
                return $http.put('/api/users/' + userData.id, userData);
                console.log(userData);
            }
        }
    }]);
    

register.html

<div class="container">

        <div class="row main"  ng-controller="UserController">
            <div class="main-login main-center">
            <h5>Sign up once for instant access.</h5>
                <form name="registerForm" ng-submit="createUser()"
                    novalidate="novalidate"
                    ng-hide="submitted" >

                    <div class="form-group">
                        <label for="name" class="cols-sm-2 control-label">Your Name</label>
                        <div class="cols-sm-10">
                            <div class="input-group">
                                <span class="input-group-addon"><i class="fa fa-user fa" aria-hidden="true"></i></span>
                                <input type="text" 
                                    class="form-control" 
                                    ng-model="formModel.name"
                                    id="name"  
                                    placeholder="Enter your Name"
                                    required="required" />
                            </div>
                        </div>
                    </div>

                    ... (Remaining HTML code omitted for brevity)

                </form>
            </div>
        </div>
    </div>
    

Answer №1

It's recommended to return a callback with the value instead of returning an HTTP raw promise from the server. Give this a try:

Service

create: function(userData, callback) {
      $http.post('/api/users', userData).then(function (res) {
            return callback(res.data); 
      }, 'error')
},

Controller

// The 'success' method is deprecated for Angular 1.5 >

// The success code returned from the server (This is not the actual error code like 404 and 500. This is just the code you received from the server) - let's say the server returns JSON format for success - {code: '0000', remark: 'Success'} and error - {code: '9999', remark: 'Success'}. This depends on your server. This is what I did in my previous project

 $scope.createUser = function() {
    if(!$scope.registerForm.$valid) {
        return;
    }
    Users.create($scope.formModel, function (res) {
         switch (res.code) {
           case '0000':
               $scope.submitting = false;
               $scope.submitted = true;
               $scope.has_error = false;
               $scope.formModel = {}; // clear the form so our user is ready to enter another
               $scope.users.push(data);
        console.log(":)");
               break;
          case '9999': 
                console.log(":(");
                $scope.submitting = false;
                 $scope.submitted = false;
                $scope.has_error = true;
                console.log('error');
               break;
      }
    });
};

If your server returns no error code and only data, you can handle it like this

 $scope.createUser = function() {
    if(!$scope.registerForm.$valid) {
        return;
    }
    Users.create($scope.formModel, function (res) {
        if (res !== undefined) {          
               $scope.submitting = false;
               $scope.submitted = true;
               $scope.has_error = false;
               $scope.formModel = {}; // clear the form so our user is ready to enter another
               $scope.users.push(data);
        } else {
                console.log(":(");
                $scope.submitting = false;
                 $scope.submitted = false;
                $scope.has_error = true;
                console.log('error');
       }
      }
    });

Answer №2

If the code provided above is accurate, then there should be no issues present. It is possible that you are overlooking some references. Feel free to check out my Plunker where your code successfully makes calls to the API.

Below is the console output from my Plunk:

in user controller
VM413 app.js:11 Object {}__proto__: Object
VM413 app.js:13 create called!!
VM413 app.js:45 create method on factory called!!
VM413 app.js:46 Object {name: "Kalyan", email: "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="740011070034001107005a171b19">[email protected]</a>", username: "tee", password: "tet", role: "1"}
VM411 angular.min.js:105 POST https://run.plnkr.co/api/users 400 ()

Click here to view my Plunk example

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

Manipulating binary data through the use of encodeURIComponent

Currently, I am reading a binary file by making a jQuery ajax get request. The file (a zip file in this instance) is returned as a string. After performing some actions on the file within the browser without modifying it, I need to send it back to a server ...

What could be the reason for the lack of controller updates despite changes made to the service

Could someone please help me solve the issue with my code? I expected that after clicking the button, the text would be updated. However, it seems to not be working as intended. Any assistance you can provide would be greatly appreciated. main.js x = a ...

A guide on implementing the fadeInRight animation effect in Angular 6

I need assistance in implementing a fadeInRight animation trigger using typescript. Currently, I have managed to implement a trigger for both fadeIn and fadeOut animations. Could someone please provide guidance on this? Please see my code snippet below: ...

Adding an object to a document's property array based on a condition in MongoDB using Mongoose

I have a situation where I need to push an object with a date property into an array of objects stored in a MongoDB document. However, I only want to push the object if an object with the same date doesn't already exist in the array. I've been e ...

Resizing the Three.js canvas without impacting the renderer size or content scaling: A guide

I am currently in the process of creating a website using a Three.js canvas that covers the entire viewport. My goal is to keep the visuals consistent even when resizing the window, without any scaling. Here is my current approach: renderer.setSize(wind ...

In Angular, there is a situation where two input fields are both referencing the same event.target

I am facing an issue where I have two input fields that are linked to the same event.target.value object, but I want them to be separate. <form class="flex-list" [formGroup]="calculation_Input" (input)="input($eve ...

Unable to upload file in angular2 due to empty Body (FormData)

Attempting to upload a photo with Angular2 to my REST Service (Loopback). The Loopback service has been successfully tested using Postman and is able to accept files with the x-www-form-urlencoded header. Below is a simplified version of the service metho ...

Determine the total number of elements across various arrays with JavaScript

I'm currently in the process of calculating the total number of elements present in all columns under taskIds. I'm uncertain about the most effective method to achieve this as I am already mapping data in the return statement. My goal is to pass ...

Incorporate JavaScript values into an HTML form to submit them to PHP

How can I successfully POST the values of 'vkey' and 'gene+varient' when submitting a form in HTML? The values are retrieved using JS code and displayed correctly on the form, but are not being sent upon submission. <form action="ac ...

Error: The status property of the response is not a valid function within the POST method at line 19 in route.js for user sign up in the app

//server.js import {connect} from "@/dbConnection/dbConnection"; import User from "@/models/userModel"; connect(); export async function POST(request, response) { try { const {username, email, password} = await request.json( ...

An error occurred while trying to access the object null in React-Native, specifically when evaluating 'this.state.token'

I encountered an error while trying to execute a class in a view: When running the class, I received the following error message: null is not an object (evaluating 'this.state.token') The problematic class that I'm attempting to render: c ...

Creating a JavaScript array using XML file attributes with jQuery

Utilizing jqGrid proves to be challenging when it comes to extracting attributes from an XML file. In order to overcome this limitation, I am seeking assistance in creating an array from the XML data provided below. The ideal array format for jqGrid is as ...

Generating JSON Data with the Power of JavaScript and JQuery

Looking to dynamically generate a JSON Object with the specified structure: { "deleteId":[1,2,3], "pointId":[1,2,3], "update":[ { "what":"mission", "id":1, "value":"adsda" }, { ...

Efficiently search and filter items across multiple tabs using a single search bar in the Ionic 2

I am currently working on implementing a single search bar that can filter lists in 2 different tabs within Ionic 2. The search bar is functional, and I have a method for filtering through objects. However, my goal is to allow users to select different tab ...

Show the React component upon clicking the Add button

I recently developed a React component that reveals a new section whenever the user clicks the "New Section" button. However, I have encountered an issue - I would like the component to display multiple sections based on how many times the button is clic ...

Creating a 3D visualization with three.js

My project requires me to create a 3D scatter graph using three.js. I have attempted to implement the code provided below. While the code is functional, the resulting graph appears more like a 2D representation. Adjusting the camera position can add depth ...

Setting up NPM on a Linux operating system

I have a goal to set up AngularJS on my system! However, in order to do so, I require npm. To install Node.js for npm, I am encountering an error: File "./configure", line 16, in <module> from gyp.common import GetFlavor File "./tools/gyp/pylib/gyp/ ...

Update Text in B-table Cell using Boostrap Vue

I need to change the text color of each cell in a column within a b-table. I have successfully changed the text color of the column header, but what about the individual cell texts? Here is the current b-table code: <b-card title="Total"> ...

When the bounds are adjusted, removing markers in Vue Cookbook's Google Map

I've encountered an issue with clearing markers after updating new bounds on a map. Whenever I post a request with new bounds, new markers get added to the map while the old ones remain in place. This situation becomes quite awkward for me because the ...

Issue with updating nested child object reference in Redux state input value

I have a function in redux that updates an object with a specified path and value. The inputs on my page are based on the values in the object stored in state. Whenever the listingObj is modified in redux, I want the DOM to automatically refresh. This i ...