What is the process for sending an object as an argument?

I've been encountering random issues with certain parts of my code.

This object is initialized within an angular controller.

this.tData = {
   'questions':[],
   'typeQuestion':[],
   'category':[],
   'dName':this.dName,
   'tCodigo':this.tCodigo}

Subsequently, I retrieve data from other functions and populate the respective fields as follows:

this.tData.questions.push(this.idQuestion) // sourced from frontend ng-model
this.tData.typeQuestion.push(this.typeQuest) // sourced from frontend ng-model
this.tData.category.push(this.idCategory)// sourced from frontend ng-model

At this point, my object is correctly constructed. When I perform a console.log(this.tData), the object appears to be fine. However, upon passing it to the backend within this function of the angular service.

this.updateStuff = function(codStuff,tData){
 return $http.put('/updateStuff' + codStuff,tData)}

The object received by the backend, as shown by console.log(params), is:

{
 questions:['exampleId'],
typeQuestion:['exampleData'],
category:[], // ISSUE OCCURS HERE
dName:'exampleName',
tCodigo:'exampleCod'}

As seen, category:[] is empty in the backend, despite displaying the correct data when using console.log(tData) in the angular service before transmission. This issue has occurred on three separate instances.

Why do some arrays successfully reach the backend while others do not?

I have attempted various solutions, but each time, one item of the transmitted object ends up empty.

If you require more specific code snippets, please let me know in the comments.

Updates

Here is where I add category information in the controller:

this.getCategoryByName = function(){
  this.bName = document.getElementById('seCategory').value;
  Category.getCategoryByName(this.bName).then((result)=>{
    this.idCategory = result.data.data._id; // obtains category ID
    this.tData.category.push(this.idCategory);
  })
  }

2

This is how I invoke my functions in the frontend:

<button class="btn btn-primary" ng-click="ctController.getCategoryByName(); ctController.updateTest();" > Update </button>

Below is the code for the updateTest() function:

this.updateTest = function(){
Test.updateTest(this.codTest,this.tData).then(result=>{})
}

This method calls the angular service updateStuff

SOLVED

The issue was resolved by implementing a chain promise in the getCategoryByName method and nesting the updateTest() method within it, similar to the suggestion by @T.J. Crowder. This adjustment provided the necessary solution.

Answer №1

In the controller, I am adding the category with this code:

this.getCategoryByName = function(){
  this.bName = document.getElementById('seCategory').value;
  Category.getCategoryByName(this.bName).then((result)=>{
    this.idCategory = result.data.data._id; // This line retrieves the category ID
    this.tData.category.push(this.idCategory);
  })
}

The issue arises from calling `updateStuff` before `Category.getCategoryByName` completes its operation, resulting in `this.tData.category.push` not being executed at the right time. The behavior that you see in `console.log` showing information from `this.tData.category` is due to deferred evaluation in the console.

This inconsistency occurs because there is a race condition between `Category.getCategoryByName` and `updateStuff`. Sometimes one function wins over the other, leading to varying results. To address this problem, `this.getCategoryByName` should return the promise chain:

    this.getCategoryByName = function(){
      this.bName = document.getElementById('seCategory').value;
      return Category.getCategoryByName(this.bName).then((result)=>{
        this.idCategory = result.data.data._id; // This gives the category ID
        this.tData.category.push(this.idCategory);
      });
    };

Furthermore, ensure that anything invoking `updateStuff` is dependent on the successful resolution of the promise. It's also essential to handle errors if `Category.getCategoryByName` fails to prevent "Unhandled rejection" errors in the console.

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

What is the best way to disable the button hover effect after it has been clicked?

Many posts I've come across have similar issues to mine, but the suggested solutions are not working for me. I am struggling to remove the hover property of my button when it is clicked before triggering the removal event I have set up. Edit: Just t ...

Developing structures for JSON that include nested arrays of objects in Swift

Having trouble parsing a JSON with a nested array of objects and struggling to understand its structure. JSON structure provided below { "data":[ { "name":"NYSC", "query":"NYSC", "tweet_volume":18478, "tweets_sata":[ ...

Exploring Object Literal Lookups in Typescript

Check out this minimal reproducible example of the issue I've created an object literal: const map = (filter: Filter) => { return { [Filter.USERS]: { fetch: async () => getUsers(), set: setUsers, }, [Filter.FIRMS]: { ...

Show the component on all routes with the exception of a few in react-router-dom version 6

In my web app, I am working on setting up various routes using react-router. Some pages require shared components like the Navigation or Footer, while others do not. What I need is a way to determine if a path does not match specific locations and only re ...

"Using .prependTo() and .insertAfter() functions without the need for jQuery

Can you explain how to achieve the following functionality without using jQuery? document.querySelector('.html-content.detail-content').insertAdjacentHTML('beforebegin', '<div id="rich-content"></div>'); I want t ...

Express server having issues with AngularJS integration

Currently delving into the world of AngularJS and experimenting with some basic examples. Successfully installed Node and utilized npm to incorporate express in the designated directory for my projects. Following a straightforward example to display an htm ...

Tips for toggling the radio button value to either checked or unchecked state

<input type="radio" name="imgsel" value="" checked /> I am looking to have a radio button that is initially checked with a value of 'present'. When the button is unchecked, I want the value to change to &apos ...

Exploring portfinder in Javascript: A guide to its usage

As a newcomer to Javascript, I am eager to figure out how to utilize the portfinder.getPort() function within one of my functions in order to generate a random port each time. The code snippet below showcases my current implementation: var portfinder = re ...

Here's a guide on executing both GET and POST requests using a single form

Currently, I am developing a web application which involves using a GET request to display checkboxes in a form. The selected data from the checkboxes needs to be sent back to the server using a POST request. However, I'm facing an issue with performi ...

When attempting to assign a 'string' type to the @Input property, I am receiving an error stating that it is not assignable to the 'PostCard Layout' type

Encountering an issue The error message 'Type 'string' is not assignable to type 'PostCard Layout'' is being displayed A parent component named page-blog.component.html is responsible for defining the class styles and passi ...

Parse XML sub-elements that are children of the main root node

Presented here is the content of an XML file named books.xml, which I am attempting to navigate: <?xml version="1.0" encoding="ISO-8859-1"?> <!-- Modified by XMLSpy® --> <bookstore> <book category="cooking"> <title lang="en"&g ...

Tips for utilizing useQuery in React JS class component:

Currently, I'm working on an app that is exclusively built using React JS class components. Since UseQuery only functions with function components and the Query tag has been deprecated, I'm facing some challenges in getting the data I need. Any s ...

Issue with displaying Git remote repository on list item element (ul) not appearing

My attempt to showcase my GitHub repositories via their API is not displaying on my webpage, even though the exact same code works perfectly fine here on JSFiddle Upon debugging, it seems that the script is being invoked but the content is not loading wit ...

Tips for successfully integrating .dae files into three.js for online execution on a web browser

Hey everyone, I'm an HTML developer who has never worked with WEBGL technology before. I've been trying to figure out how to pass a .dae file into 'three.js' by searching through numerous websites, but I haven't been successful. C ...

Having trouble with an endless loop while utilizing useLazyQuery in React with Apollo and GraphQL?

In the progress of my code, it appears like this: const { ID } = useParams(); const [getObjects, {loading, data}] = useLazyQuery(GET_OBJECTS_BY_ID); const objectWithID = props.data.find(datum => datum._id == ID); if (objectWithID.conditional) { get ...

Having trouble executing the npm start command for ReactJS

Below is the code snippet from my file named server.js if(process.env.NODE_ENV !== 'production') { require('dotenv').parse() } const express = require('express') const app = express() const expressLayouts = require(' ...

What is causing the angular ng-repeat table to not sort correctly?

Currently, I am facing an issue with a table that is being populated by Angular: I have provided the code here so you can see the problem in action: http://plnkr.co/edit/qzY4r2XWq1UUJVrcqBsw?p=preview When I click on the a elements, the sort order change ...

Conceal choices within a Vimeo video

Is it possible to conceal specific elements such as the title, logo, like and watch buttons on a Vimeo video while still displaying the play/pause button? I attempted to use CSS and JavaScript to accomplish this, but was unsuccessful due to the video being ...

When constructing a file directory URL, it is important to utilize the forward slash "/" in the filename

As I am creating a URL, the process involves taking the filename and using it to create a folder with that name. However, an issue arises if the name contains "/", as it causes the URL to break and creates an undesired location. For example: var fileDir ...

What could be causing the inability to retrieve the HTML content of $(window['iframeName'].document.body) when I modify the .attr('src') method?

Why isn't it functioning $(window['iframeName'].document.body).html() ...properly when I update the .attr('src')? When I initially set the src attribute of the iframe to a URL upon creating the page, this code $(window['i ...