Exploring the relationship between two entities in Angular 7 using Typescript

Creating a Reactive form for user registration in Angular involves setting up the form data object separately from the viewmodel object.

https://i.sstatic.net/ERlYa.png

export interface RegisterViewModel {
UserName: string;
Email: string;
Password: string;
ConfirmPassword: string; }

To clarify, in the form object, the password properties are nested within a separate 'matching_passwords' object.

The onSubmit(value) method captures the form object.

  onSubmit(value) {
this.accountService.register(value)
.pipe(first())
.subscribe(
  data => {
    console.log('successful registration');
    this.router.navigate(['/login']);
  },
  error => {
    console.log('unsuccessful registration');
  }); }

This method passes the value to the service, which expects the RegisterViewModel object.

  register(viewModel: RegisterViewModel) {
    return this.http.post<any>('api/Account/Register', viewModel, httpOptions)
      .pipe(map(data => {
        return data;
      }));
  }

How do I map these different objects without changing the form structure to perfectly match the RegisterViewModel?

What is the best way to pass the form model values to the register method, register(viewModel: RegisterViewModel), ensuring that the RegisterViewModel receives all necessary fields?

Answer №1

To create the object, you simply need to use the form values. Looking at your image, the process would be as follows:

// assuming your form value object is called `form_values` (not `value` like in your code)
const userViewModel = <RegisterViewModel> {
  Username: form_values.userName,
  EmailAddress: form_values.email,
  Password: form_values.matching_passwords.password,
  ConfirmPassword: form_values.matching_passwords.confirmPassword
};

After that, you simply make the call:

this.accountService.register(userViewModel)
// ... rest of the code remains unchanged

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

The property 1 cannot be added because the object is not extendable in React

Does anyone know what is causing the following issue? I am unable to insert a new object into a key object within my arrays of objects. For example, when I try to insert a new email at index 1 in the 'emails' array, it throws an error stating "ca ...

Is it possible to pass additional arguments to setState other than prevState and props?

I'm currently facing an issue with my component that involves calling a function called addOption, which is defined on its parent component. This function takes a parameter 'option' from a form field and concatenates it with an array of opti ...

I'm encountering an issue trying to apply array filtering with checkboxes using React hooks and TypeScript

Help needed! I'm facing an issue while trying to filter an array based on gender using checkboxes. The functionality works fine for the male checkbox but seems to fail when clicking on the female checkbox. Below is the code snippet from my App.tsx fil ...

What is the best way to customize a button component's className when importing it into another component?

Looking to customize a button based on the specific page it's imported on? Let's dive into my button component code: import React from "react"; import "./Button.css"; export interface Props { // List of props here } // Button component def ...

Tracking code execution in React, Enzyme, and Istanbul reveals uncovered functions running during tests

I have been working on testing a React component that involves 3 functions. The tests I've written for these functions pass successfully, but my code coverage report indicates only a 33% coverage. Here is the code snippet of the component: const AddW ...

Access to private members is restricted when redefining a class method

After defining a private member with #, attempting to redefine a member that utilizes this private member will result in the inability to access it: class Foo { #secret = "Keyboard Cat"; method() { console.log(this.#secret); } } ...

TypeScript function object argument must be typed appropriately

In the code, there is a function that I am working with: setTouched({ ...touched, [name]: true }); . This function accepts an object as a parameter. The 'name' property within this object is dynamic and can be anything like 'email', &ap ...

An error occurred while trying to load the configuration "next/core-web-vitals" for extension

If you're embarking on a new project using NextJs and TypeScript, chances are you may encounter the following error: Failed to load config "next/core-web-vitals" to extend from. Wondering how to resolve this issue? ...

Creating a customizable filter by using the function of an object

I am currently developing a customizable dynamic filter system, similar to the functionalities offered by Yahoo Screener. To achieve this, I have defined an interface for the available filter fields: export interface FilterField { label: string; se ...

Upon subscribing to an observable, the initial value is invariably null

Here is an example of the ProfileService I am currently using: export class ProfileService { private user: BehaviorSubject<User> = new BehaviorSubject<User>(null); constructor(private userService: UserService) { this.userService.getUs ...

I'm experiencing difficulties in establishing a connection from Ionic to my remote database

I set up a database on Fauxten and now I'm trying to connect it to my project. Although I can open the link in my browser, nothing happens when I try to call it in the app. I can't figure out what I'm missing. import { Injectable } from &ap ...

When you use map to transform the value, Observable will consistently return as undefined

Can anyone help me figure out why, when I transform the observable, it returns undefined in the console log even though there are assigned values? HTTP Request getLibraryCardPeople(bookName: String): Observable<people[]> { return this.http.get<Li ...

How to dynamically incorporate methods into a TypeScript class

I'm currently attempting to dynamically inject a method into an external class in TypeScript, but I'm encountering the following error. Error TS2339: Property 'modifyLogger' does not exist on type 'extclass'. Here's the ...

Despite having data, ngrx continues to display the error message 'Typerror: entities.reduce is not a function'

I am diving into the world of ngrx entity dataservice for the first time The API call successfully retrieves the expected datahttps://i.sstatic.net/74GAU.png However, ngrx encounters an error while processing it, specifically on the reduce method https:/ ...

Searching in TypeScript tables with Angular's search bar

I've successfully completed a basic CRUD application, but now I need to incorporate a Search Bar that can filter my table and display rows with matching letters. I'm unsure how to approach this in my component. I've seen examples using pipe ...

Issue occurred with Firebase geoFire setting: unable to access properties of undefined when reading 'pieceNum_'

Recently, I decided to update my old Ionic Angular app and upgraded the firebase module to version 9.23.0 along with the geofire module to version 6.0.0. However, upon calling the set function on geoFire with an id and an array of coordinates, I encountere ...

Tips for keeping an Angular Material Dialog component at the forefront of your application's layout

My application is designed with a vertical Navigation Bar positioned on the left side of the screen, and a Home Component displayed in the <router-outlet> to its right. However, I am facing an issue where when I open a Dialog Component within the H ...

Exploring Angular 5: Managing HTTP Headers and Utilizing URL Parameters

I am currently working on an Angular project that involves third-party authentication, which redirects to our app with additional information in the HTTP headers. Here are the questions I have: What is the best way to extract the information from the HT ...

Retrieve the TaskID of an ECS Fargate container for exporting and future use within AWS CDK code

Currently, I am leveraging CDK version 2 alongside Typescript. In my current setup, I encounter a situation where I necessitate the TaskID value from ECS Fargate Container to be incorporated into another command. The process involves me utilizing new ecs ...

Unable to locate any NativeScript modules for tns-core-module/ui

I'm working on a {N}-Application and facing an issue with importing Images from the tns-core-modules/ui/image module. Unfortunately, it seems that the target cannot be found within the tns-core-module. This is my code snippet: import * as ImageModul ...