What is the best way to retrieve the value of this object?

In my project, I am utilizing Angular 8 to extract data from a radio input. However, when I transmit this data to Node.js and then to a MongoDB database, it is not being properly registered. The entry in the database collection appears as follows:

"__v" : 0

The data output sent from Angular is: { type: administrator }, but what I actually want to store in the database is just the word adminstrator. The Node.js console displays an error due to receiving an object instead of the expected string value.

Here is the Angular template code:

<br>
<div class="w3-panel w3-border w3-margin" style="width: 500px; height: 550px">

        <label class="w3-text-blue"><h2>New User</h2></label>
        <label class="w3-text-blue"><b>Name and Last Name</b></label><br>
           <input type="text" class="w3-input w3-border" [(ngModel)]="name" ><br>

        <label class="w3-text-blue"><b>User</b></label><br>
           <input type="text" class="w3-input w3-border" [(ngModel)]="user"><br>

        <label class="w3-text-blue"><b>Password</b></label><br>
           <input type="password" class="w3-input w3-border" [(ngModel)]="password"><br>

        <label class="w3-text-blue"><b>Confirm Password</b></label><br>
           <input type="password" class="w3-input w3-border" [(ngModel)]="confirm"><br>

        <label class="w3-text-blue"><b>Type of User</b></label><br>

        <form #myForm="ngForm" (submit)="sendRadio(myForm.value)" >
            <input id="administrator" type="radio" name="type" class="w3-radio" value="administrator" ngModel>
               <label for="administrador">Administrator</label> <br>
            <input id="normal" type="radio" name="type" class="w3-radio" value="normal" ngModel>
               <label for="normal">Moderator</label>
     <br><br>
        <button type="submit" (click)="createUser(user, password, name)" class="w3-button w3-round-xxlarge w3-green">Create</button>
        <button class="w3-button w3-round-xxlarge w3-red">Clean Fields</button>
</form>

</div>

The TypeScript file for the component:

import { Component, OnInit } from '@angular/core';
import { PersonService } from '../_services/person.service';

@Component({
  selector: 'app-create-user',
  templateUrl: './create-user.component.html',
  styleUrls: ['./create-user.component.css']
})
export class CreateUserComponent implements OnInit {

  user: any;
  password: any;
  confirm: any;
  name: any;
  type: string;

  constructor(private ps: PersonService) { }

  ngOnInit() {
  }

  sendRadio(value: any) {
    this.type = value;
    console.log(this.type);  // <--- this outputs { type: administrator }
  }

  createUser(userU, userPassword, userName) {
    if (this.password === this.confirm) {
       if (this.password.length > 0 && this.confirm.length > 0) { 
          this.ps.createUser(userU, userPassword, userName, this.type);
          } else {
            console.log('Password has to match and be completed');
            }
    }else {
        console.log('Password does not match');   

    }
  }
}

The service used to send the data (PersonService):

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';

@Injectable({
  providedIn: 'root'
})
export class PersonService {

  uri = 'http://localhost:3000';

  constructor(private http: HttpClient) { }

  createUser(userU, userPassword, userName, userType: string) {
    const obj = {
      user: userU,
      password: userPassword,
      name: userName,
      type: userType
    };
    this.http.post(`${this.uri}/createUser`, obj)
    .subscribe(res => console.log('User has been created'));
  }

Answer №1

To obtain the desired output, simply input:

console.log(this.type.type);

You should retrieve the value associated with the key for type. The result will display 'administrator', allowing you to transmit this information to your backend node effectively.

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

Angular 5: Utilizing distinct router-outlets in separate modules for optimized lazy loading experience

Having two modules with routing module files and router-outlets in their html, I aim to load components based on the current module. The file tree structure is as follows: project |-- module2 |-- -- profil |-- -- - profil.component.html |-- -- - profil. ...

Support for time-series data in MongoDB through ingestion from Debezium

My server receives data from multiple devices generated by their sensors. This telemetry data is stored in json format in a partitioned table named statuses in a postgresql database. The table is partitioned monthly on the columns time_stamp and device_id, ...

React Query mutation encountered a TS2554 error: Type argument was not valid

I'm a beginner when it comes to TypeScript and I am using react-query. I tried using mutate, but it is causing an error. TS2554: Expected 1-2 arguments, but got 3. interface: interface ChangePassword{ email: string; password: string; conf ...

Sometimes encounter undefined values after assigning them through the service

One of the challenges I am facing is handling public fields in my service: @Injectable() export class ShareDataService { // Some code public templateForCurrencyCOS; public templateForPercentCOS; public templateForCurrencyCOGS; public te ...

I'm just starting out with jQuery and JSON and could use some assistance with formatting the string, specifically so I can properly iterate through it

This is the controller. <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> @RequestMapping("/getDropDownAjax") public void fetchData(HttpServletRequest req,HttpServletResponse resp){ System.out.println ...

Unveiling JSON file in DNN: A step-by-step guide

I recently developed a DNN module in ASP.NET that relies on data stored in locator.json. Now, I am trying to transition it to DNN platform but encountering issues as DNN is unable to locate the json file. Can someone please advise me on the specific fold ...

Utilizing Jquery ajax to retrieve JSON data from a web service

Instead of utilizing a page WebMethod, I am considering using jQuery ajax call to retrieve JSON data from C# .NET. Currently, the response I receive in JSON format appears as follows: {"d":"{\"ID\":1,\"Value\":\"First Value&bsol ...

Decoding JSON in Objective C with integer key names incremented consecutively

I'm having some trouble figuring out how to parse this JSON data. It's structured in a way that I'm not quite used to: "nodes": { "4": { "node_id": 4, "title": "TITLE 1", "description": "", }, "7": { ...

What is the most effective way to retrieve the top five maximum results from a sub document using

I am relatively new to using mongo db and although I have a basic understanding of it, I still have some questions. Below is a collection of albums that I currently have: { "_id" : ObjectId("5f9ff607562cdb1c5c2acb26"), "t ...

In Angular 12, the button click should only proceed once a method with an HTTP call has finished executing

Users can input multiple search criteria into the form and initiate a search operation by clicking the search button. Some of the fields in the search criteria form are dropdowns. Choosing a value from a dropdown triggers an API call to retrieve a specifi ...

Tips for sorting out JSON data by specific key parameters and eliminating any redundant information

I am presenting a Json object with the following structure: var initialdata = [ { "type": "Feature", "properties": { "Region": "US", "SubRegion": "US-1", "SiteID&quo ...

In the function ngOnChange, the SimpleChange currentValue is supposed to be defined, but for some reason, the

Within the TypeScript code, a name variable is assigned input from another component. @Input() name : any ; In the ngOnChange function, I retrieve and print the SimpleChange object in the following manner. ngOnChanges(changes: SimpleChange){ console.l ...

Executing a series of API calls using Rxjs in Angular that result in a null response

I encountered a situation where I needed to make sequential API calls using RxJs in Angular. However, despite successfully implementing the calls, I am struggling with a null error. In this scenario, the second API call depends on receiving an id from the ...

Angular service is continuously throwing the error message "NullInjectorError: No provider for anotherService"

I recently built a basic Angular service and encountered an issue. @Injectable() export class someHandler { constructor( public anotherService: anotherService, ) {} ... The problem arises when I try to use this service in a component, as ...

Guide to setting up JQ through Mac terminal

Can someone please provide me with instructions on the best method for installing JQ on Mac (El Capitan)? I have already downloaded the code to my Mac, but I am not sure how to install and use it through the command line. Thank you! ...

Attempting to access a specific JSON key using Observables

Apologies for the question, but I'm relatively new to Typescript and Ionic, and I find myself a bit lost on how to proceed. I have a JSON file containing 150 entries that follow a quite simple interface declaration: export interface ReverseWords { id ...

Implementing the handling of multiple button events in a ListView through onclick function

Currently, I have a listview with three buttons that need to trigger the same method checkInstall on multiple button clicks. However, I am unsure of how to achieve this. Below is the relevant code snippet: html file: <ListView [items]="allAppsList" c ...

The 'validate' property within the 'MappingService' class cannot be assigned to the 'validate' property in the base class 'IMappingService' in typescript version 2.8.0

Currently, I am utilizing the AngularJS framework (version 1.5.8) in tandem with the latest TypeScript files (2.8.0). However, upon updating to the newest version of TypeScript, the code below is failing to compile. The IMappingService interface: export ...

Bringing in a script and invoking a function on a specific variable

As a newcomer to Typescript, I've been experimenting with some code I came across online to enhance the appearance of links on my website. <script src="https://wow.zamimg.com/widgets/power.js"></script> <script>var wowhead_tooltips ...

Using React with Typescript to display components generated from the `map` function

In my scenario, I have retrieved data from a JSON file and am also utilizing a utility function that selects 5 random entities from an object Array. This particular array contains 30 entities. Struggling with displaying the 5 random jockeys stored in the ...