Utilizing Angular JS to execute a callback function upon receiving data from a Web Service

Attempting to incorporate a controller callback function within my service, triggering upon the success of an $http post request. The code snippet below provides a more detailed description.

Controller :

function UserAccountCtrl (UserService, $rootScope, listUsers) {
    $rootScope.title = 'Comptes utilisateurs';
    this.users = listUsers.data;
  this.isShown = false;
  this.isModification = false;

    this.deleteEntry = function(entry){
    this.users.splice(this.users.indexOf(entry), 1);
    UserService.delete(entry); 
  };

  this.show = function(){
    this.isShown = true;
  };

  this.hide = function(){
    this.isShown = false;
  };

  this.save = function(){
    var success = function(data){
      this.users.push(data);
    };

    var err = function(data){
      alert(data);
    };

    UserService.post(this.user, success, err);
    this.hide();
  };
}

Service Function :

UserService.post = function (data,succ,err) {
    $http({
        url: __ADRS_SRV__ + "user",
        method: "POST",
        data:data,
        isArray: true
    }).success(function(data){
       succ(data);
    }).error(function(error){
        err(error);
    });
}

The process is straightforward: after posting a new user, the WebService adds it to mongo and sends back the newly created object. Retrieving the new object through console.log or an alert works perfectly fine.

However, I'm encountering an issue when attempting to push the new item into my array. An error message pops up stating:

Uncaught TypeError: undefined is not a function

This error occurs exactly where I try to push the new item into the array.

If anyone has any insights or suggestions, they would be greatly appreciated.

Thank you in advance

Answer №1

this in this.users.push(data); is referring to a different context than the one outside of the function. As a result, there is no users array available to push the new data into. For more information on how `this` works in JavaScript, check out MDN this.

In order to avoid this issue, it may be better to avoid using this altogether and instead attach everything to the $scope object as needed. This ensures that $scope remains consistent regardless of the context.

function UserAccountCtrl ($scope, UserService, $rootScope, listUsers) {
    $scope.users = listUsers.data;
    $scope.save  = function(){
        var success = function(data){
            $scope.users.push(data);
        };

        var err = function(data){
             alert(data);
        };

        UserService.post($scope.user, success, err);
        $scope.hide();
   };
   // repeat the same pattern for other functions
}

For further insights, you can also refer to 'this' vs $scope in AngularJS controllers.

Answer №2

Could you please test if this is functioning correctly?

this.send = function(){
    var self = this;
    var onSuccess = function(data){
      self.list.push(data);
    };

    var onError = function(data){
      alert(data);
    };

    UserService.post(this.item, onSuccess, onError);
    this.hide();
  };

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 drawback of invoking an async function without using the await keyword

Here is the code snippet containing an async function: async function strangeFunction(){ setTimeout(function(){ //background process without a return //Playing Russian roulette if ( Math.random() > 0.99 ) throw n ...

Steps to handle the change event of a p:inputText element

In my current setup, I am utilizing p:inputText and have the need to trigger a javascript function that will update the searchField in the backend bean. <p:inputText required="true" placeholder="#{cc.attrs.searchTip}" value="#{cc.attrs.queryProperty}" ...

The error message "Uncaught TypeError: Object #<a Document> has no method 'write'" appears

Encountered an error when trying to integrate the Google Visualization API into a page on Google App Engine while using Chrome's developer tools console: Uncaught TypeError: Object # has no method 'write' In Firefox 3.5, the error displayed ...

Which task is prioritized for execution?

With my PHP web application, I am unsure which code will be called and processed first. Inside my PHP file, there is also a block of JavaScript: <script> $(document).ready(function(){}); </script> In the PHP code, I send an array object to t ...

The uib-datepicker-popup is failing to reopen

I'm encountering an issue with the uib-datepicker-popup where once I select a date from the calendar, I am unable to reopen it without refreshing the screen. I've checked the ng-click function and it correctly sets the is-open flag to true, but t ...

The script functions perfectly in jsfiddle, yet encounters issues when used in an HTML

I stumbled upon a seemingly peculiar issue with my script in jsfiddle: https://jsfiddle.net/oxw4e5yh/ Interestingly, the same script does not seem to work when embedded in an HTML document: <!DOCTYPE html> <html lang="en"> <head> & ...

Create folders and .js files with ease using command line automation

In my React app project, I find myself repeatedly copying and pasting three specific files to a new directory whenever I create a new component. These files include import statements at the top and a class declaration within the body. Is there any way for ...

Synchronize data across variables or set up a listener for changing variable values?

Imagine I have a scenario with 2 variables: var connection1, connection2; connection1 = connection2 = false; There are 2 distinct functions that establish connections to a remote node and update each variable to true once connected: node1.on('open& ...

Use JavaScript to input array elements into a selection of cells in Excel

At this moment, the loop I am executing successfully retrieves the necessary values. However, I am facing challenges when it comes to inserting these array values into a range of cells. I keep encountering the following error message: Error message: "The ...

Combine and showcase various rows into one row using ng-repeat

I am looking to merge and display particular data in a single row with the same id. I am currently using ng-repeat to show the data. Sample JSON: $scope.sampleTest = [{"city": "Chennai", "name":"Sample"}, {"city": "Madurai", "name":"Test" ...

What is the optimal method for interacting with a backend service in AngularJS?

As a newcomer to AngularJS, I am seeking advice on the best approach to tackle my current issue. The challenge at hand involves dealing with a service that returns a rather intricate JSON object like the one shown below (but even more intricate!): var com ...

Developing a custom directive that utilizes a dynamic ng-options configuration

Alright, let me share with you my personalized directive: angular.module('bulwarkWebControls', []) .directive('customDropdown', [ function() { return { scope: { label: '@', // can be om ...

Trouble with toggling div visibility using jQuery and AJAX

I'm trying to display a specific div based on the result of an SQL query. The problem I'm facing is that I can't seem to toggle the divs asynchronously. Currently, the page needs to be reloaded for the div to reflect the changes. <?ph ...

Can someone help me figure out the issue with my Angularjs ng-repeat implementation?

After spending hours trying to figure out why something so simple is not working, I'm at a loss. Testing with a dummy list proves the functionality works, but when I connect my server-side data source, it fails. The JSON returned from the AJAX call i ...

The Server Side Rendering in (Vue+Express) faltered due to inconsistencies in hydration

While browsing Vue's official website, I came across a concise example demonstrating how to implement server-side rendering (SSR) using Vue. (https://stackblitz.com/edit/vue-ssr-example-qaztqn?file=package.json) Intrigued by this example, I decided ...

collect information from text box

Is it possible to retrieve data entered into input fields that have not been submitted and display that data in another div by clicking a button? Can this task be accomplished using scripting languages? HTML <form> <div class="div1">< ...

Discovering the precise Offset value for a Div element

Looking for a way to identify the unique value of each div on my HTML page, even as offset values change with each refresh. Any suggestions or methods that can help achieve this? ...

Issue with AngularJS promise not returning any value in JavaScript

I have been attempting to perform a simple HTTP post in a unit test using Jasmine, but unfortunately, it is not functioning as expected. The application operates smoothly on the web, and I have individually tested various functions, all of which work seaml ...

The Click Event Is Triggering Even with Correct Callbacks Being Set

I am struggling to understand why these functions are not executing properly. I know the correct syntax for binding a function, like this: $('#idOfThing').bind('click', foofunc); function foofunc() { ///do things } However, I am facin ...

Why is it important to incorporate an inner function in order to return to the outer function?

Can you explain the distinction between these two functions, bind_1 and bind_2? function bind_1(f, o) { if (f.bind) return f.bind(o); else return function() { return f.apply(o. arguments); }; } function bind_2(f, o) { if (f. ...