angular - 如何在 Angular 中使用 HttpClient GET 方法?
问题描述
首先对不起我的英语不好。我是 Angular 的新手。我的网站使用了一个 asp.net 核心 Api。我尝试登录用户。我的用户界面是:
export interface iuser{
username: string;
login: string;
password: string;
roles: string[];
}
我也有一个具有此功能的 AuthService:
SignIn(login: string, password : string): Observable<iuser> {
let apiUserAccount: string = environment.apiAddress + 'UserAccount/' + 'Login?' + 'login=' + login + '&' + 'password=' + password;
return this.http.get<iuser>(apiUserAccount);
}
在我的组件中,我这样称呼这个功能服务:
onSubmit() {
this.submitted = true;
if (this.loginForm.invalid) {
return;
}
this.loading = true;
this.AuthService.SignIn(this.f.login.value, this.f.password.value)
.subscribe(response => {
this.user = response as iuser
console.log('User = ' + this.user.username);
});
if(this.user == null){
this.router.navigate(['/']);
}
}
用户是这样声明的:
user!: iuser;
我的 api 服务被调用并返回用户,但 Angular 项目中的属性用户始终是“未定义”。我不明白为什么?
有谁能帮助我吗?谢谢。
解决方案
您正在 http 调用后立即检查用户。由于它是异步的,因此不会立即设置它的值。您也必须在订阅中移动路由器导航,但我建议您使用finalize 运算符。当调用完成或出错时调用它。
onSubmit() {
this.submitted = true;
// You should always negate the `valid` property, as when the `FormGroup` is in `"DISABLED"` state, both `valid` and `invalid` properties are set to `false`;
// Or you can check with `this.loginForm.state === 'VALID'`.
if (!this.loginForm.valid) {
return;
}
this.loading = true;
this.AuthService.SignIn(this.f.login.value, this.f.password.value)
// Use the finalize operator
.pipe(finalize(() => {
this.loading = false;
if(this.user == null){
this.router.navigate(['/']);
}
}))
.subscribe(response => {
this.user = response as iuser;
console.log('User = ' + this.user.username);
});
}
推荐阅读
- spring - 根据值有条件地自动连接 bean 实现?
- arrays - 如何在本机反应中显示来自哈希的数据?
- php - 在 wordpress 中合并 PHP GD 库中的两个图像时,图像不显示
- html - 在 HTML 中选择特定值后如何使选择组可供选择
- excel - 在使用 VB.NET DLL 的 Excel VBA 中,DLL 是否可以包含操作活动工作簿单元格/范围/等值的代码?
- javascript - 甜蜜警报后的文件上传窗口
- c# - 如何使实体框架 DbContext 通用用于动态连接字符串?
- android - 使 Android 库中的类只能从测试代码访问
- wordpress - Woocommerce 产品包中的产品属性和变体
- python - Line.strip() 在 python 中不起作用?