Another return payload failing to retrieve the return value

I'm currently facing an issue where a function that should return a value is not being passed on to another function. Below is the code snippet in question:

public _getProfileToUpdate() {
  return {
    corporateId: this.storeService.setStoreData().profile.preferred_username[1],
    id: this.storeService.setStoreData().profile.sub,
    firstName: this.userFormGroup.controls.firstName.value,
    lastName: this.userFormGroup.controls.lastName.value,
    email: this.userFormGroup.controls.email.value,
    mobile: this.userFormGroup.controls.mobile.value,
    workNumber: this.userFormGroup.controls.workNumber.value,
    roleId: this.sortRoleId()
  };
}

sortRoleId() {
  this._contentService._getRoles().subscribe((resp) => {
    const search = this.storeService.setStoreData().profile.role;
    const index = Object.values(resp.roles).indexOf(search);
    const result = Object.keys(resp.roles)[index];
    return result;
  })
}

I am trying to send the "result" value to the "roleId" field in the other function, but it seems to be returning as undefined.

Answer №1

Give this a shot:

function fetchProfileToUpdate() {
    // Call the service
    this._contentService.fetchRoles().subscribe((response) => {
        const searchQuery = this.storeService.updateStoreData().profile.role;
        const index = Object.values(response.roles).indexOf(searchQuery);
        const key = Object.keys(response.roles)[index];
        
        // Prepare and return object
        return {
            corporateId: this.storeService.updateStoreData().profile.preferred_username[1],
            id: this.storeService.updateStoreData().profile.sub,
            firstName: this.userFormGroup.controls.firstName.value,
            lastName: this.userFormGroup.controls.lastName.value,
            email: this.userFormGroup.controls.email.value,
            mobile: this.userFormGroup.controls.mobile.value,
            workNumber: this.userFormGroup.controls.workNumber.value,
            roleId: key
        };
    })
}

Answer №2

To efficiently manage the subscription to the content service, consider subscribing in your ngOnInit method or adjust the calling hierarchy of your methods like this:

profile = {};
public _getProfileToUpdate() {
this._contentService._getRoles().subscribe((resp) => {
const search = this.storeService.setStoreData().profile.role;
const index = Object.values(resp.roles).indexOf(search);
const result = Object.keys(resp.roles)[index];
// Return object
this.profile = {
corporateId: this.storeService.setStoreData().profile.preferred_username[1],
id: this.storeService.setStoreData().profile.sub,
firstName: this.userFormGroup.controls.firstName.value,
lastName: this.userFormGroup.controls.lastName.value,
email: this.userFormGroup.controls.email.value,
mobile: this.userFormGroup.controls.mobile.value,
workNumber: this.userFormGroup.controls.workNumber.value,
roleId: result
};
})
}

Handle the variable within your form or application, and Angular will automatically trigger the necessary functions to process updated information.

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

Issue encountered while retrieving value from asynchronous dns.lookup() function

I am currently in the process of developing a function that validates a url by utilizing the dns.lookup() function, which is outlined below: const dns = require('dns'); const verifyURL = (url) => { const protocolRegEx = /^https?:\/& ...

How can I use JQuery to enable or disable checkboxes upon loading?

I am looking to implement a feature where the checkboxes are enabled when the .group is checked and disabled when it is unchecked. Although I can toggle between them, I'm facing difficulty in disabling the unchecked checkbox using the .group. Upon lo ...

Informing Typescript that a variable has already been null-checked

An unusual yet structurally sound code snippet is presented below: function doFoo(food: string | null = null) { food = food ?? getFood(); // getFood: () => string | null if (!food) { throw Error("There's still no food :("); } plate[fo ...

Guide on transmitting data from a child component to a parent object in Vue.js?

When I attempt to utilize a child component with custom form inputs and emit those values to the parent component, I encounter an issue where one input value disappears when another input value is entered. Let me showcase some code: Child Component <tem ...

What is the best way to send the selected option from a dropdown to a button click function within the controller?

I need to pass the selected value from a user's country selection dropdown to the ng-click="saveChanges()" function on the submit button. Is there a correct method for achieving this? I want to be able to access the user's selection from the dro ...

What is the best way to divide a string that contains n concatenated JSON strings in JavaScript or Node.js?

Imagine I receive the following string from a socket server (which is out of my control): {"data":{"time":"2016-08-08T15:13:19.605234Z","x":20,"y":30}}{"data":{"time":"2016-08-08T15:13:19.609522Z","x":30,"y":40}} Because it contains 2 JSON strings, using ...

Managing the response from a variable returned by jQuery's .load method

I am facing an issue with my code. I am using jQuery post to validate whether the name of the filter is available for use. $.post('check-username.php', $("#myform").serialize(), function(data) { alert(data); }); When I use the alert to disp ...

Encountered a style group error 'non-collision' while using Angular with HERE Maps JS API 3.1

Occasionally, I encounter an error when trying to load a HERE map with the satellite base layer: Tangram [error]: Error for style group 'non-collision' for tile 13/16/15542/12554/15 Cannot read property 'retain' of undefined: TypeE ...

Merge JSON object information into tables, including column headings

I am currently facing a challenge in loading multiple JSON files into tables within different divs. Here is the structure of my JSON data: JSON file 1: [ { "id": 12345, "code": "final", "error": "", "data": [ ...

Use PHP to highlight the row that has been selected in an HTML table

I am currently working on a project where I have styled multiple HTML tables on my website using alternating gray and white bands. Now, my goal is to highlight the selected row in a darker shade of gray. I have experimented with various solutions, and the ...

Problem with sending variable via AJAX

Hey everyone, I'm attempting to send form data along with an extra variable using AJAX. Here's the code snippet: function tempFunction(obj) { var data = $('form').serializeArray(); data.push( { no: $(obj).at ...

The tooltip menu options in material ui are displaying in a different location in the window rather than below the button icon. How can this issue be resolved?

I'm having trouble implementing a tooltip on an option menu icon and it's not working as expected. Here is my code: export default function FadeMenu() { const [ anchorEl, setAnchorEl ] = React.useState(null) const bus = Bus() const o ...

Exploring various components within a JavaScript array

I keep a list of names in a file named Ignore.json [ "George", "Carl" ] The filename is ignore.json Within my program, I load the contents of the file into a variable called ignore var ignore; ignore = require("./Ignore.json"); Now, I need to check i ...

Abrupt surge in Firestore read operations detected in Next.js application following a period of no modifications - refer to the accompanying visual

https://i.sstatic.net/vim7m.png During the initial 10 days of working on the project, I noticed a consistent range of reads between 100 - 300 per day while regularly refreshing documents from firestore. Days 11-15 were spent away from the project visiting ...

Reorganizing an array using a custom prioritized list

Is it possible to sort an array but override precedence for certain words by placing them at the end using a place_last_lookup array? input_place_last_lookup = ["not","in"]; input_array = [ "good", "in", "all&qu ...

Is it possible that Angular2 is unable to properly establish the default value when it is selected?

I've been attempting to establish a default value for my selection by using [selected]= "selected_choice == 'one'" similar to this method but unfortunately, it didn't yield the desired result. Upon hearing that [selected] is no long ...

Is there a way to alter the text color using JavaScript on the client side?

Is there a way to change the color of a list item in a ul based on whether it is a palindrome or not? Here is the JavaScript file I am working with: function isPalindrome(text){ return text == text.split('').reverse().join(''); } c ...

Creating visual content on Canvas using JavaScript

Having an issue with stacking multiple images on separate Canvas layers, and they're not drawing on the canvas. Can anyone help me figure out what I'm missing? Thanks CSS .positionCanvas{ position: absolute; left:0; righ ...

Creating a JavaScript function using jQuery to calculate the total sum of textboxes with two specified classes

I'm currently attempting to calculate the total of a group of textboxes by utilizing jquery. Each textbox is styled with a class (class1) using bootstrap. To execute the jquery function, I've added an extra class (class2). Below is an example of ...

Parsing JSON sub items in Android application using Java

Here is a snippet of my PHP file: <?php $myObj = array( "name"=>"John" , "age"=>"30" , "post"=>[ "title"=>"What is WordPress" , "excerpt"=>"WordPress is a popular blogging platform" , ...