The AngularJS Service fails to properly convert incoming Json Responses into Model objects during piping

I have been studying AngularJS 17 and recently developed a login application. However, I am facing an issue where the server response is not being properly mapped to the object in the Model Class.

Response:

    {
    "id": 1,
    "userName": "admin",
    "email": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="2243464f4b4c62454f434b4e0c414d4f">[email protected]</a>",
    "password": "",
    "role": 1,
    "token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VybmFtZSI6ImFkbWluIiwiaWF0IjoxNzA1NzQwMTkzLCJleHAiOjE3MDU3NDE5OTN9.obH83er-eb0Pcl_OLXhwPj7kXUy9lNh0EK3NInr3Eas"
}

Model:

export class LoginViewModel {
    UserName: string;
    Password: string;
    constructor(){
        this.UserName = "";
        this.Password = "";
    }
}

Service:

public Login(loginViewModel: LoginViewModel): Observable<LoginViewModel> {
return this.httpClient.post<LoginViewModel>(this.NODE_HOST + "/api/authenticate",loginViewModel,{responseType: "json"}).pipe(
  map(user =>{
    if(user) {
      var userData = JSON.parse(JSON.stringify(user));
      this.currentUser = user.UserName;
      console.log("userData-UserName: ", userData.userName);
      console.log("User: ", JSON.stringify(user));
      sessionStorage.setItem('currentUser', JSON.stringify(user));
    }
    return user;
  })
);

}

Within the service code, I found a workaround by using stringify and then parsing the data to obtain the user data in JSON format. However, it feels like a messy solution.

In a Udemy course on Angular 11, the instructor was able to automatically receive the data into the ModelClass, but in my case (Angular 17), this automatic mapping is not happening as expected.

Answer №1

It seems like there is a discrepancy in the case between your API (using username) and your interface (using UserName). Making sure they match could potentially resolve the issue!

Consider removing the third argument for the post method, as providing just the URL and post body should suffice.

Angular will automatically convert the API response to an object, eliminating the need for

JSON.parse(JSON.stringify((user))
.

Make adjustments to the interface if requests expect userName instead of UserName. Otherwise, it may not be necessary.

export class LoginViewModel {
    userName: string;
    password: string;
    constructor(){
        this.userName = "";
        this.password = "";
    }
}

service

public Login(loginViewModel: LoginViewModel): Observable<LoginViewModel> {
return this.httpClient.post<LoginViewModel>(this.NODE_HOST + "/api/authenticate", loginViewModel).pipe(
  map(user =>{
    if(user) {
      const userData = user; // <- changed here
      this.currentUser = user.userName; // <- changed here
      console.log("userData-UserName: ", userData.userName);
      console.log("User: ", JSON.stringify(user));
      sessionStorage.setItem('currentUser', JSON.stringify(user));
    }
    return user;
  })
);

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

"Utilizing Firebase Functions to update information in the Firebase Realtime Database on a daily basis

Currently, I am in the process of working on a project where I aim to provide users with a daily percentage of points based on their current available points and update this data in my Firebase database. My goal is to add points for users on a day-to-day b ...

How to access a variable from outside a promise block in Angular

Is there a way to access a variable declared outside of a promise block within an Angular 6 component? Consider the following scenario: items: string[] = []; ngOnInit() { const url='SOME URL'; const promise = this.apiService.post(url ...

A Promise is automatically returned by async functions

async saveUserToDatabase(userData: IUser): Promise<User | null> { const { username, role, password, email } = userData; const newUser = new User(); newUser.username = username; newUser.role = role; newUser.pass ...

Ways to set a background image for two separate components in Angular

Trying to figure out how to integrate this design: The challenge lies in having a background image that spans across the navbar and the content below it. Currently, the code separates the navbar component from the content component, making it tricky to ac ...

Error in Visual Studio when attempting to create a new Angular file without proper authorization

After setting up node, npm, and angular cli, I encountered an UnauthorizedAccess error when creating a new project in Visual Studio. Can someone please offer some assistance? Thank you, Please see the attached error image for reference ...

Transferring data from a child component to a parent component in Angular using @ViewChild requires providing 2 arguments

Currently, I am attempting to transmit data using @Output & EventEmitter and @ViewChild & AfterViewInit from a child component to a parent component. Below is the code from my parent component .html file: <app-child (filterEvent)=" getValu ...

When the button is clicked, a fresh row will be added to the table and filled with data

In my table, I display the Article Number and Description of werbedata. After populating all the data in the table, I want to add a new article and description. When I click on 'add', that row should remain unchanged with blank fields added below ...

Rendering Information in Angular 4 Through Rest API

Encountering issues displaying data from my local express.js REST API, organized as follows: people: [{ surname: 'testsurname', name: 'testname', email: '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemai ...

Having trouble with Angular 2 and Ionic2 mocks? Getting an error message that says "No provider

Currently in the process of creating a spec.ts file for my application. The challenge I'm facing is related to using the LoadingController from ionic-angular. In order to configure the module, it requires providing the LoadingController (due to its pr ...

The Angular checked functionality is not working as expected due to the presence of ngModel

Just getting started with Angular here. I’m working on a checkbox table that compares to another table and automatically checks if it exists. The functionality is all good, but as soon as I add ngModel to save the changes, the initial check seems to be ...

Leveraging WebStorm's TypeScript support in conjunction with node_modules

Attempting to set up a TypeScript project in WebStorm to import a Node.js module has been a struggle. I made sure to download the necessary TypeScript definition in settings and specified --module commonjs in the compiler settings. However, I keep running ...

A more efficient method for querying documents based on ids that are not in a given list and then sorting them by a specific publish date

After implementing the code provided below, I noticed that the performance tests indicate each request takes a second or longer to complete. My goal is to enhance this speed by at least 10 times. The bottleneck seems to be caused by the NOT operator resu ...

Next.js TypeScript project encountered an issue: "An error occured: 'TypeError: Cannot read property 'toLowerCase' of undefined'"

I am currently developing a Next.js TypeScript project and am facing a perplexing runtime error. The error message reads: TypeError: Cannot read property 'toLowerCase' of undefined This error is triggered in my code when I try to invoke the toLo ...

On a mobile device, the keyboard is hiding the PrimeNG dropdown

While my dropdown works flawlessly on a desktop browser, I encountered an issue when accessing it on an Android device. The dropdown immediately disappears and the virtual keyboard pops up, which is not the case on iOS devices. I suspect that the problem ...

Tips for implementing HTTP requests in Angular 2 without TypeScript

The demonstrations provided by the angular team only illustrate injecting Http for typescript. https://angular.io/docs/js/latest/api/http/Http-class.html How can this be accomplished in JavaScript? import {Http, HTTP_PROVIDERS} from 'angular2/http& ...

Error: The version of @ionic-native/[email protected] is not compatible with its sibling packages' peerDependencies

When attempting ionic cordova build android --prod, the following error occurred: I have tried this multiple times. rm -rf node_modules/ rm -rf platforms/ rm -rf plugins/ I deleted package.lock.json and ran npm i, but no luck so far. Any ideas? Er ...

Trouble displaying JSON data in HTML using *ngFor in Angular

Just starting out with angular and I've created a services class that returns product details in JSON format. api.service.ts import { Injectable } from '@angular/core'; import { Http } from '@angular/http'; import 'rxjs/add/ ...

Instruction Leads to Input Losing Focus

I have developed a custom directive for allowing only numbers in an input field: @Directive({ selector: 'input[numbersOnly]' }) export class NumbersOnlyDirective { constructor(private ref: ElementRef, private control: NgControl) { } @Hos ...

Your global Angular CLI version (6.1.2) surpasses that of your local version (1.5.0). Which version of Angular CLI should be used locally?

I am experiencing an error where my global Angular CLI version (6.1.2) is higher than my local version (1.5.0). Can someone provide assistance with this issue? Below are the details of my local versions: Angular CLI: 1.5.0 Node: 8.11.3 OS: win32 ia32 Ang ...

Discover the steps to update the rows, adjust the number of results, and manage pagination in angular-datatable with an observable as the primary data source

Incorporating angular-datatables into my Angular 7 application has been a challenge, especially when it comes to displaying search results efficiently. Within the request-creation-component, a search form is generated. Upon clicking the submit button, an ...