我是 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");
}
}
我还有一个用于创建用户对象的用户界面。我知道以这种方式处理凭据是不安全的,请原谅我,现在我只是在试验。非常感谢!
海绵宝宝撒
相关分类