Unable to distribute the returned object received from the server

Currently, I have taken over a project initiated by a colleague, and I am encountering difficulties with an API call. Here is the snippet of my angular controller code:

angular.module('oowli').factory('Note', ['$http', function($http) {
  var Note = function(data) {
    angular.extend(this, data);
  };

  Note.prototype.save = function() {
    var note = this;
    return $http.post('/notes', this).then(function(response) {
      note = response.data;
    }, function(error) {
      return error;
    });
  };

  return Note;
}]);

The API call is made within this function:

var saveNote = function(Note, scope){
        return function(span, phrase){
            var noteObj = new Note({
                user: scope.global.user._id,
                content: span.innerText
            });
            noteObj.save().then(function(){
                console.log(noteObj);
            });

        };
    };

My concern lies in the fact that after saving the note, the noteObj remains unchanged instead of being updated with the returned object from the server (containing an _id field). Upon debugging within the Note.prototype.save, it is evident that response.data contains the _id;

I am seeking guidance on how to access the updated Note object within the saveNote function.

Answer №1

In the Note.prototype.save function, you are assigning a new object to the local variable 'note', but then not utilizing it further.

An alternative solution would be to copy the properties of the returned object to your note instead of directly assigning it like this:

note = response.data;

You could try this approach:

angular.copy(response.data, note)

However, I personally prefer not having the Note class handle its own saving process. It would be better to create a separate note service for this purpose.

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

Tips on invoking a function from an array in JavaScript when a button is clicked

Being new to JavaScript, I encountered a challenge where I have an array of functions: allFunctions = () => [ function1(), function2(), function3(), function4(), function5(), function6(), function7(), function8(), function9() ] My go ...

Is it possible to check if something is "ready" by using a combination of setTimeout and recursive functions?

I am currently working on a solution to determine when an asynchronous call is "ready" or not. I have a function that uses $.ajax which, upon success, sets a boolean variable in the global scope and some other data. Prior to making the ajax call, the boole ...

"The website seems to be experiencing some technical difficulties on Firefox, but I have switched to

I attempted to reset the text area after sending a message with the code below: $(document).keypress(function (e) { if (e.which == 13) { e.preventDefault(); var $form = $('#f1'); $.ajax({ url: $form.attr( ...

What is preventing me from injecting a directive into my test cases?

While I have been successful in injecting various things in the beforeEach(inject(beforeEach(inject(function(_$controller_,_mycustomService_,_$log_) in Jasmine, there is one challenge I'm facing when trying to inject a directive. Despite being able ...

Error encountered with underscore template - Unforeseen SyntaxError: Unexpected token <

I encountered an error when attempting to load one of my underscore templates. It seems to be related to an issue in the for loop, which I suspect should be a .each loop, but I'm still trying to grasp its structure. Here is a snippet of my template: ...

Loading content synchronously

Could you assist me in finding a solution to synchronize the loading of pages and elements? Currently, my code looks like this: $(Element).load(File); ... other commands... window.onload = function () { Update_Elements(Class, Content); } Everything ...

Changes made to code within the node_modules directory do not appear in the browser

I encountered a bug in the vuejs-datepicker project on Github, prompting me to fork the repository. However, despite making changes to the forked project, these alterations are not reflected in my main project that relies on this dependency. Here's a ...

Eliminate negative values in CSS using jQuery

In my AngularJS project, I am utilizing jqLite for some custom CSS properties implementation. Here is an example of how I am incorporating the custom CSS properties: $scope.$on('scrollEvent', function(){ if (a < 5){ a = a + 1/2 ...

Data merging in Firebase 9 and Vue 3 is not functioning properly

I am facing an issue with merging data in my firebase database. I consulted the documentation at https://firebase.google.com/docs/firestore/manage-data/add-data for guidance. After attempting to merge data using setDoc, I encountered an error (Uncaught Ty ...

Using Node/Express to split the request headers with the .split() method

I am currently working on a way to determine if a specific item exists in the req.headers in order to make a decision on what to send back to the user. Here is my code snippet: function serveAppData(req, res) { console.log("CHECKME", req.headers); //var h ...

Is there an efficient method for matching "data-" attributes with property names in mixed case?

In my custom jQuery plugins, I utilize a base plugin class that goes beyond what the jQuery UI widget offers by handling more complex tasks. Currently, I am looking to extract values from data- attributes attached to elements and incorporate them as optio ...

Modify nested JSON in JavaScript, much like how Ruby translations can interpret them (from a list or text)

I have a specific goal in mind. My JSON data is multi-level, structured like this: var json = { 'first_level': { 'second_level': ['one', 'two'] }, 'another_first_level': true } and I want ...

Unable to scale image to full size using JavaScript

Seeking assistance on optimizing the width of a JavaScript slider to be 100%. Below is my existing HTML: <div id="mhblindsshow"> <style type="text/css"> #mhblindsshow img { display:none; } </style> <a href="blog ...

creating a div that functions similarly to a radio button

Is it possible to create a div that mimics the behavior of a radio button? I'm looking for a solution that doesn't involve jquery, as many people have recommended. After doing some research, I found a few potential options. In the past, I'v ...

PHP - Issue with submitting form data using $_POST from within a Div text container

Having some trouble with the submission of the "about_me_container" div in my form using $_POST. I know that divs are not typically used with $_POST, so I tried changing the div to input type="text" and textarea but it still won't work. I also attempt ...

A guide on utilizing express.js to retrieve and display the output of a mySql query

I am facing an issue with getting the results of my simple SELECT command into the index.js file. I want to store all the records in an array, but when I try to do so, I always end up with undefined values. Interestingly, if I print the results in the data ...

Jasmine: Methods for verifying if the accurate URL is invoked during a GET request

I need to test a service function, but I'm unsure how to mock an internal service function that is called within the main function. My goal is to verify if the correct URL is being accessed. Below is the code snippet for my service: angular.module(" ...

Implementing automatic pagination based on container height using jQuery

Looking to convert an AngularJS fiddle into jQuery. The goal is to create pagination using several p tags only with jQuery. Current code: <div class="parent"> <p>text1</p> <p>text2</p> <p>text3</p> ...

Steering clear of Unique error E11000 through efficient handling with Promise.all

In my development work, I have been utilizing a mongoose plugin for the common task of performing a findOrCreate operation. However, I recently discovered that running multiple asynchronous findOrCreate operations can easily result in an E11000 duplicate k ...

Switching templates in AngularJS

We have a unique challenge from our client who wants a responsive website, but desires to make significant content changes that may push the limits of bootstrap. Although bootstrap allows for showing/hiding blocks and adjusting their positions with offset ...