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

Unable to change the visibility of blockquotes using jquery

Currently, I am delving into the world of basic JQuery functions. My main focus right now is figuring out how to display the active blockquote while keeping the others closed or closing them. Essentially, creating a toggle effect where only one blockquote ...

Shared validation between two input fields in Angular 2+

I have a unique task at hand. I am working on creating an input field with shared validation. The goal is to ensure that both fields are technically required, but if a user fills in their email address, then both fields become valid. Similarly, if they ent ...

Tips on retrieving enum values in typescript

Having trouble retrieving values from an enum? Check out this snippet of code: export const enum ComplianceType { ENGINEER_ASSESMENT = 'ENGINEER_ASSESMENT', CONSTRUCTION_COMPLIANCE = 'CONSTRUCTION_COMPLIANCE', ARCHITECTURE_ASSIGN ...

Is it possible to retrieve 2 arguments within a function in a non-sequential manner?

Let's say there is a function with arguments A, B, C, D, and E. Function(A, B, C, D, E) However, not all arguments are needed all the time. For instance, only A and C are needed in some cases. Currently, I would have to call the function like this: Fu ...

A guide to transferring modules between component files in JavaScript

My query pertains to the handling of imports in web pages. When a file is imported into another, do the declarations and imports from the imported file become available in the file where it is being imported? A suggestion was made for me to import a compo ...

Managing the behavior of screen readers when interacting with forms

I have a form in my Angular 2 application with input fields. The JAWS 18 screen reader reads the input fields one by one when the page is loaded. I want to customize this behavior so that the screen reader only mentions the form and then stops. I tried u ...

Optimal method for a React and HTML Select-component to output String values instead of Integer values

Within my React-class (JSX), I've included the following code: var Select = React.createClass({ onChange: function (ev) { console.log(ev.target.value); }, render: function() { var optionsHtml = this.state.options.map(function (el) { ...

How do I delete an element from an array in a MongoDB database using Node.js?

When running this query in ROBO 3T, the code executes correctly. However, when attempting to run it in nodejs, the code is not functioning as expected. //schema model const mongoose = require('mongoose'); const imageSchema = mongoose.Schema({ ...

Is there a way to determine the position of the highlighted text within a textarea?

Is there a simple way to calculate the position of the selected text within a textarea using vanilla JavaScript or Angular (possibly with a directive)? This is important in order to display a div with a popup above the selected text. Coordinates are need ...

Transforming a base64 encoded string into a byte array

I have implemented a form where users can upload images to the page using an <input id = "fileLoader" type = "file" />. With JavaScript, I convert these uploaded images to base64 and send them to the server. On the server side, I need to decode this ...

Ember controller failing to update template upon property set within promise execution

I am facing an issue while integrating user login functionality in my application. After retrieving the user data from the server, I aim to display the user's name on the page once the process is completed. The login form appears as a popup window, in ...

Understanding how to utilize jQuery or prototype to interpret onclick event containing "setLocation(...)" can enhance the functionality

I am dealing with a specific tag: <button onclick="setLocation('http://mysite.com/checkout/cart/add/product/17/')" /> My goal is to trigger an ajax request when the button is clicked. I want to extract the URL segment "product/17" and app ...

How can the color of the wishlist icon be modified in Reactjs when the item is available in the database?

Is there a way to change the color of the wishlist icon based on whether the item is in the database? If the item is present, its color should be brown, and if it's not present, the color should be black. Additionally, I want the ability to toggle be ...

How to Implement Route Resolution for Nested Components in Angular 4?

In my current setup, I have the following hierarchy: Parent Component |__Nested Component 1 |__Nested Component 2 |__Nested Component 3 The challenge I am facing is resolving data into Nested Component 3 since only the Parent Component has a rout ...

How can I trigger a JavaScript function when the ENTER key is pressed?

I'm attempting to use JavaScript to scroll down a page. The code below works perfectly when I use javascript:pageScroll() in a link or button: <SCRIPT LANGUAGE="Javascript"> function pageScroll() { window.scrollBy(0,50); // hor ...

Transform the outcome of Request() into a variable

I'm currently working with the following code snippet: request('http://steamcommunity.com/market/priceoverview/?currency=1&appid=730&market_hash_name=Gamma Case', function (e, r, body){ var req_data = JSON.parse(body); conso ...

How to use a filtering select dropdown in React to easily sort and search options?

Recently, I started learning React and created a basic app that utilizes a countries API. The app is able to show all the countries and has a search input for filtering. Now, I want to enhance it by adding a select dropdown menu to filter countries by reg ...

What is the reason behind VS Code not showing an error when executing the command line tsc shows an error message?

Deliberately introducing a typo in my code results in an error. Here is the corrected code: declare const State: TwineState; If I remove the last character and then run tsc on the command line, it throws this error: tsc/prod.spec.ts:7:22 - error TS2304: ...

Getting the value from the object that holds the Provider/Consumer using React's Context API

Below is a demonstration using the Context API object with a library called 'react-singleton-context'. Check it out here. In my Menu.js file, I have the code snippet console.log(useSharedDataContext()). This displays an object containing Consume ...

Angular 2 - Changes in component properties not reflected in view

I'm currently delving into Angular 2 and as far as I know, interpolated items in the view are supposed to automatically update when their corresponding variable changes in the model. However, in the following code snippet, I'm not observing this ...