I am doing a POST api call for user authentication with httpclient in Angular 13/TypeScript 4.4.4. I can check the response model content and it seems ok, but if I access a property of the model, it is undefined.
This is the response model:
import { UserAccountStatus } from "./Enums";
export interface AuthResponseModel {
UserLoginId: number;
AccountStatus: UserAccountStatus;
}
Here the service POST call:
import { HttpClient, HttpErrorResponse, HttpHeaders } from '@angular/common/http';
import { Injectable, Inject } from '@angular/core';
import { Observable, throwError } from 'rxjs';
import { catchError } from 'rxjs/operators';
import { AuthResponseModel } from '../shared/AuthResponseModel';
import { LoginModel } from '../shared/LoginModel';
const httpOptions = {
headers: new HttpHeaders({
'Content-Type': 'application/json'
})
}
@Injectable({
providedIn: 'root'
})
export class AuthService {
constructor( private http: HttpClient ) { }
private get APIUrl(): string {
return this.token;
}
Login( username: string, password: string ): Observable<AuthResponseModel> {
const url: string = 'https://test.com/api/Auth/Login';
const loginModel: LoginModel = {
Username : username,
Password : password
};
return this.http.post<LoginModel>( url, loginModel, httpOptions )
.pipe(
catchError( this.errorHandler ) );
}
private errorHandler( error: HttpErrorResponse ): Observable<any> {
console.error('Error occured!');
return throwError( () => error );
}
}
And here is my login form, where the service is used:
import { OnInit, Input, Component, Output, EventEmitter } from '@angular/core';
import { FormGroup, FormControl } from '@angular/forms';
import { lastValueFrom } from 'rxjs';
import { AuthService } from '../services/auth.service';
import { AuthResponseModel } from '../shared/AuthResponseModel';
@Component({
selector: 'app-login',
templateUrl: './login.component.html',
styleUrls: ['./login.component.css']
})
export class LoginComponent implements OnInit {
loginForm!: FormGroup;
authResp?: AuthResponseModel;
constructor(private authSrv: AuthService) { }
async submit() {
if ( this.loginForm.valid ) {
const resp$ = this.authSrv.Login( this.loginForm.value.username, this.loginForm.value.password );
this.authResp = await lastValueFrom( resp$ );
if ( this.authResp ) {
const id: number = this.authResp.UserLoginId // <- undefined
const dbg: string = JSON.stringify( this.authResp );
console.log(dbg); // <- ok with the correct value (...UserLoginId: 3)
}
}
}
ngOnInit(): void {
this.loginForm = new FormGroup({
username: new FormControl(''),
password: new FormControl(''),
});
}
}
What am I missing here? Something with map?
This is the dbg output:
{"userLoginId":3,"accountStatus":5}
CodePudding user response:
The server respond with userLoginId (lowercase u) and accountStatus (lowercase a), so this.authResp.UserLoginId is undefined.
Your model should be
export interface AuthResponseModel {
userLoginId: number;
accountStatus: UserAccountStatus;
}
CodePudding user response:
Finally I solved the problem. It was due to the property names in the reponse model. I am using asp.net core web api with upper-case first character in the property names and also here in angular, respectively typescript. I noticed that the stringyfied json is in lower-case first character. So I changed the model names in the angular part:
export interface AuthResponseModel {
userLoginId: number;
accountStatus: UserAccountStatus;
}
With this correction it is working.
CodePudding user response:
To me looks like your actually not waiting return from this.authSrv.Login.
async login( username: string, password: string ): Observable<AuthResponseModel> {
const url: string = 'https://test.com/api/Auth/Login';
const loginModel: LoginModel = {
Username : username,
Password : password
};
await return this.http.post<LoginModel>( url, loginModel, httpOptions )
.pipe(
catchError( this.errorHandler ) );
}
async submit() {
if ( this.loginForm.valid ) {
const resp$ = await this.authSrv.Login( this.loginForm.value.username, this.loginForm.value.password );
this.authResp = await lastValueFrom( resp$ );
if ( this.authResp ) {
const id: number = this.authResp.UserLoginId // <- undefined,respectively 0
const dbg: string = JSON.stringify( this.authResp );
console.log(dbg); // <- ok with the correct value (...UserLoginId: 3)
}
}
Also ts people tend to keep methods camelCase starting with lowercase so I renamed Login to login.
