我正在使用 Angular 13/TypeScript 4.4.4 中的 httpclient 進行 POST api 呼叫以進行用戶身份驗證。我可以檢查回應模型內容,看起來還可以,但是如果我訪問模型的屬性,它是未定義的。
這是回應模型:
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}
uj5u.com熱心網友回復:
userLoginId服務器以(lowercase u) 和accountStatus(lowercase )回應a,因此this.authResp.UserLoginId未定義。
你的模型應該是
export interface AuthResponseModel {
userLoginId: number;
accountStatus: UserAccountStatus;
}
uj5u.com熱心網友回復:
最后我解決了這個問題。這是由于回應模型中的屬性名稱。我正在使用 asp.net core web api,屬性名稱中的第一個字符大寫,這里也使用 angular,分別是 typescript。我注意到 stringyfied json 是小寫的第一個字符。所以我改變了角度部分的模型名稱:
export interface AuthResponseModel {
userLoginId: number;
accountStatus: UserAccountStatus;
}
有了這個更正,它就可以作業了。
uj5u.com熱心網友回復:
在我看來,您實際上并沒有等待從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)
}
}
ts 人也傾向于保持方法 camelCase 以小寫開頭,所以我將 Login 重命名為 login。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/422837.html
標籤:
