首页 > 解决方案 > 如何在 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 项目中的属性用户始终是“未定义”。我不明白为什么?

有谁能帮助我吗?谢谢。

标签: angularrxjs

解决方案


您正在 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);
    });
}

推荐阅读