我是 Angular 的新手,對打字稿不太精通,所以我很難看出這里出了什么問題。我正在編寫一個簡單的登錄表單,詢問“用戶名”和“密碼”,并在后端調用一個 API 來驗證憑據。該 api 有效,我也能夠在我的組件中收到正確的響應,但只能在表單的第二次(或以后)“提交”時。在第一次提交時,我得到一個ERROR TypeError: Cannot read property 'password' of undefined. 從第二個開始,我的控制臺記錄“登錄成功等”。我希望它在第一次嘗試時記錄成功!由于我在第二次提交時得到了正確的響應,因此該 api 可以正常工作,所以我認為它是一個順序邏輯錯誤或一個實際的打字稿語法錯誤......感謝任何幫助。組件: constructor( private http: HttpClient, private _studentService: StudentService) { } ngOnInit(): void { } user: User; submit(name: string, pass: string):void{ // console.log(name, pass); this._studentService.getUserByUsername(name).subscribe(data => this.user = data); this.verify(this.user.password, pass); } verify(checkPsw: string, pass: string){ if (checkPsw==pass){ console.log("Login Successful " + this.user.username + this.user.userID); //logging this to see if the request comes through correctly since the ID is not in the form, and it is correct, so api works. }else{ console.log(this.user.password, pass); } } }模板基礎:<form (submit)="submit(username.value, password.value)"> <input #username name='studUsrn' class="form-control"> <input #password type="password" name='studPswd' class="form-control"> <button type="submit" class="btn btn-primary">Login</button></form>服務:@Injectable({ providedIn: 'root'})export class StudentService { constructor(private http:HttpClient) {} private _restUrl: string = "http://localhost:4200/users"; //make an http call and receive a response getAllUsers(): Observable<User[]>{ return this.http.get<User[]>(this._restUrl).pipe(catchError(this.errorHandler)); } getUserByUsername(username: string): Observable<User>{ console.log(this._restUrl+"/"+username); return this.http.get<User>(this._restUrl+"/"+username).pipe(catchError(this.errorHandler)); } errorHandler(error: HttpErrorResponse){ return throwError(error.message || "Server Error"); }} 我還有一個用于創建用戶對象的用戶界面。我知道以這種方式處理憑據是不安全的,請原諒我,現在我只是在試驗。非常感謝!
第一次以角度提交表單時出現“TypeError無法讀取未定義的屬性”
滄海一幻覺
2022-10-08 10:11:54