Embrace AngularJS: Employ the ".then" method and retrieve the response

In order to send a http request and receive the response of this request, I am trying to implement a mechanism where if the data is successfully saved, I can retrieve database information, and if it fails to save, I can track errors. To achieve this, I plan to utilize the .then method in angularjs. I have created an angularjs controller and services to handle this functionality. Below is the code snippet from the angularjs part:

bolouk.js:

'use strict';
var app = angular.module('app');
app.controller('BoloukCtrl', ['$scope', 'Bolouks', function($scope, Bolouks){
$scope.save = function(){
        Bolouks.create($scope.bolouk).then(function(data){
        $scope.saveBolouk = data;
        },function(err){
                $scope.err = err;
            }
        );
    };
}]);

boloukService.js:

'use strict';
var app = angular.module('boloukService', ['ngResource']);
app.factory('Bolouks', function($resource) {
    return $resource('/api/bolouks.json', {}, {
        create: { method: 'POST', isArray: false }
    });
});

Additionally, I have included the following code on the rails server side: bolouks_controller.rb:

  def create
    @bolouk = Bolouk.create(bolouk_params)
    if @bolouk.valid?
      #@bolouk.save
      respond_with @bolouk, :location => api_bolouks_path
    else
      respond_with @bolouk.errors, :location => api_bolouks_path
    end
  end
  private
  def bolouk_params
    params.require(:bolouk).permit(:boloukcode, :north, :south, :east, :west)
  end

Even though the request is sent correctly to the rails server and the data is saved in the database without any issue, I am facing difficulties in retrieving the response of the request. When I run the function, I encounter the following error in the chrome console:

TypeError: undefined is not a function
    at Scope.$scope.save (http://localhost:3000/assets/controllers/bolouk.js?body=1:19:39)
    at http://localhost:3000/assets/angular.js?body=1:10973:21
    at http://localhost:3000/assets/angular.js?body=1:20088:17
    at Scope.$eval (http://localhost:3000/assets/angular.js?body=1:12752:28)
    at Scope.$apply (http://localhost:3000/assets/angular.js?body=1:12850:23)
    at HTMLFormElement.<anonymous> (http://localhost:3000/assets/angular.js?body=1:20087:21)
    at HTMLFormElement.jQuery.event.dispatch (http://localhost:3000/assets/templates/jquery-1.10.2.js?body=1:4627:9)
    at HTMLFormElement.elemData.handle (http://localhost:3000/assets/templates/jquery-1.10.2.js?body=1:4295:46) 

I suspect that there might be an issue with how I am using the .then method in the angularjs controller. I have also explored the $q method but still faced the same error. Any suggestions or insights on how to resolve this problem would be greatly appreciated.

Answer №1

Make sure to assign each module in a separate variable to avoid code conflicts. Here is an example of how you can do this:

bolouk.js:

'use strict';
var app = angular.module('app',['ngResource']);
app.controller('BoloukCtrl', ['$scope', 'Bolouks', function($scope, Bolouks){
$scope.save = function(){
        Bolouks.create($scope.bolouk).$promise.then(function(data){
        $scope.saveBolouk = data;
        })
        .catch(function (err) {
          console.log(err);

      })
    };
}]);

boloukService.js:

'use strict';

app.factory('Bolouks', function($resource) {
    return $resource('/api/bolouks.json', {}, {
        create: { method: 'POST', isArray: false }
    });
});

Answer №2

var app = angular.module('app',['boloukService']);


app.controller('BoloukCtrl', ['$scope', 'Bolouks', function($scope, Bolouks){
    $scope.save = function(){
        var user = Bolouks.get();
        user.get(function(resp) {
            //request successful
        }, function(err) {
            //request error
        });
    };
}]);

angular.module('boloukService', ['ngResource']);
    app.factory('Bolouks', function($resource) {
    var userData = {}

    function fetchUserData() {
        return  $resource('/api/bolouks.json', {}, {
            create: { method: 'POST', isArray: false}
        });
    }
    return {
        get: fetchUserData
    }
});

Give this code a try :)

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 content within the div appears to be in a perpetual state

I'm working on creating a chat application with a single interface. I've encountered an issue where the content in the middle div "messages" keeps bouncing, including the scroll bar. How can I resolve this problem? Additionally, I'm unable ...

Tips for binding to a single input box within an ngFor loop

Can anyone lend a hand with some code? I'm working on a straightforward table using ngFor, but I'm facing an issue with input binding. The problem is that all the input fields generated by ngFor display the same value when typing. How can I preve ...

Ways to display an error notification alongside another message

I have set up a validation directive that requires users to check a box. If the checkbox is left unchecked, an error message will be displayed. However, I am facing an issue where the message overlaps with the checkbox text. https://i.sstatic.net/iTKoo.jp ...

I am a beginner in the world of MEAN stack development. Recently, I attempted to save the data from my form submissions to a MongoDB database, but unfortunately, I have encountered

const express = require('express'); const bodyParser = require('body-parser'); const mongoose = require('mongoose'); mongoose.connect('mongodb://localhost/test'); const Schema = new mongoose.Schema({ username: St ...

The module "ng-particles" does not have a Container component available for export

I have integrated ng-particles into my Angular project by installing it with npm i ng-particles and adding app.ts import { Container, Main } from 'ng-particles'; export class AppComponent{ id = "tsparticles"; /* Using a remote ...

Sinon and Chai combination for testing multiple nested functions

I attempted to load multiple external JavaScript files using JavaScript. I had a separate code for the injection logic. When I loaded one JavaScript file, the test case worked fine. However, when I tried to load multiple JavaScript files, the test case FA ...

Is it not possible to apply the .includes method on a string within a v-if directive while utilizing a computed property?

Problem I am facing an issue while trying to determine if a string contains a substring within the Vues v-if directive. The error message I receive is: TypeError: $options.language.includes is not a function The technologies I am using are Vue, Vuex, and ...

The popover displays the text "[object Object]" when triggered by an ajax event

Upon observing the image, I noticed that my bootstrap popover is triggering and displaying “[object Object]” instead of the database data I retrieved. After adding logs to the JavaScript AJAX code, I can see that the data is being retrieved, but it i ...

Retrieve information from a database using PHP and assign it to a JavaScript variable

I need to display a Google map marker on my website, with the latitude and longitude values coming from the database in the columns labeled latitude and longitude. Here is the initial JavaScript code: var map; function initialize() { map = new GMaps( ...

Angular/JS - setTimeout function is triggered only upon the occurrence of a mouse click

I'm currently working on a website that calculates the shortest path between two points in a grid utilizing AngularJS. Although I have already implemented the algorithm and can display the colored path, I am facing an issue where the color changes ti ...

The Vue.js v-on:mouseover function is not functioning properly in displaying the menu

When I hover over a LI tag, I want to display a menu. I have successfully implemented it using a simple variable with the following code: @mouseover="hoverFormsControls=true" @mouseleave="hoverFormsControls=false" However, when I attempted to use an arr ...

Stopping a build programmatically in Next.js involves implementing specific steps that aim to halt

Is there a method to programmatically halt the execution of npm run build in Next.js when a specific Error occurs within the getStaticProps function? Simply throwing an Error does not seem to stop the build process. ...

How to implement ngx-spinner in an Angular http subscribe operation

I'm trying to incorporate a spinner into my Angular Application using ngx-spinner. I've come across this library but haven't found enough practical examples on how to use it effectively. Specifically, I want to integrate the spinner with my ...

JavaScript can be utilized to alter the style of a cursor

I'm currently developing a browser game and incorporating custom cursors into it. To ensure the custom cursor is displayed throughout the entire page, I've applied it in my CSS (though setting it up for 'body' occasionally reverts back ...

What is the best way to transform a standard select input into a React select with multiple options?

Is it possible to transform a regular select dropdown into a multiple select dropdown in React, similar to the one shown in this image? I'm currently using the map method for my select options. https://i.stack.imgur.com/vJbJG.jpg Below is the code s ...

How can I resize an element using jQuery resizable and then revert it back to its original size with a button click?

I need help figuring out how to revert an element back to its original size after it has been modified with .resizable. I attempted the following: <!DOCTYPE html> <html> <head> <link rel="stylesheet" href="//code. ...

Error: Koa.js framework is unable to find the "users" relation in the Sequelize database

I am currently facing an issue while attempting to establish a relationship between two tables, 'user' and 'accessToken'. The error message I am encountering is hindering the process. Below are the models in question:- User model:- ...

The issue lies with Express Mongoose failing to store the data

Encountering some issues when trying to save an object created in Express nodejs using mongoose. Despite receiving a confirmation that the object is saved, it cannot be located even after attempting to access it through the server. Express route for savi ...

What is the process for transferring image attributes to the server via a URL?

My data transmission process only involves sending data. Below is the data I send: export const cabin = { name: '001', maxCapacity: 2, regularPrice: 250, discount: 0, image: './cabins/cabin-001.jpg', description: ...

Tips for launching and troubleshooting an AngularJS application within Eclipse

Looking to dive into Nodeclipse and get up and running with debugging an AngularJS application like the angular-phonecat example from Eclipse. Specifically, I want to utilize a Debug on Server launcher to kick off a server with my app and launch a web b ...