Angular 13 api 调用中未定义响应模型参数
Response model parameter is undefined in Angular 13 api call
我正在 POST api 调用 Angular 13/TypeScript 4.4.4 中的 httpclient 进行用户身份验证。我可以检查响应模型内容,看起来没问题,但如果我访问模型的 属性,它是未定义的。
这是响应模型:
import { UserAccountStatus } from "./Enums";
export interface AuthResponseModel {
UserLoginId: number;
AccountStatus: UserAccountStatus;
}
此处服务 POST 调用:
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 );
}
}
这是我的登录表单,使用该服务的地方:
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(''),
});
}
}
我在这里错过了什么?有地图吗?
这是 dbg 输出:
{"userLoginId":3,"accountStatus":5}
在我看来,你实际上并没有在等待 this.authSrv.Login
。
return
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)
}
}
而且人们倾向于让方法以小写字母开头,所以我将 Login 重命名为 login。
我终于解决了这个问题。这是由于响应模型中的 属性 个名称。我正在使用 asp.net 核心网络 api,在 属性 名称中使用 upper-case 第一个字符,在 angular 中也使用打字稿。我注意到字符串化 json 在 lower-case 第一个字符中。所以我在 angular 部分更改了模型名称:
export interface AuthResponseModel {
userLoginId: number;
accountStatus: UserAccountStatus;
}
通过此更正,它正在运行。
服务器响应userLoginId
(小写u
)和accountStatus
(小写a
),所以this.authResp.UserLoginId
未定义。
您的模型应该是
export interface AuthResponseModel {
userLoginId: number;
accountStatus: UserAccountStatus;
}
我正在 POST api 调用 Angular 13/TypeScript 4.4.4 中的 httpclient 进行用户身份验证。我可以检查响应模型内容,看起来没问题,但如果我访问模型的 属性,它是未定义的。
这是响应模型:
import { UserAccountStatus } from "./Enums";
export interface AuthResponseModel {
UserLoginId: number;
AccountStatus: UserAccountStatus;
}
此处服务 POST 调用:
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 );
}
}
这是我的登录表单,使用该服务的地方:
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(''),
});
}
}
我在这里错过了什么?有地图吗?
这是 dbg 输出:
{"userLoginId":3,"accountStatus":5}
在我看来,你实际上并没有在等待 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)
}
}
而且人们倾向于让方法以小写字母开头,所以我将 Login 重命名为 login。
我终于解决了这个问题。这是由于响应模型中的 属性 个名称。我正在使用 asp.net 核心网络 api,在 属性 名称中使用 upper-case 第一个字符,在 angular 中也使用打字稿。我注意到字符串化 json 在 lower-case 第一个字符中。所以我在 angular 部分更改了模型名称:
export interface AuthResponseModel {
userLoginId: number;
accountStatus: UserAccountStatus;
}
通过此更正,它正在运行。
服务器响应userLoginId
(小写u
)和accountStatus
(小写a
),所以this.authResp.UserLoginId
未定义。
您的模型应该是
export interface AuthResponseModel {
userLoginId: number;
accountStatus: UserAccountStatus;
}