首页 > 解决方案 > 必须单击带有角度的单击事件两次才能完成操作

问题描述

我的按钮有问题。该按钮是一个登录按钮。当我在输入凭据后单击 Enter 时,会触发查看凭据是否正确的方法。这工作没有任何问题。

但也应该发生的是,在检查这些凭据是否正确之后,应该删除登录和注册按钮以及将出现的新配置文件按钮。

为了使前面的事情发生,我必须再次按下按钮,这些按钮才会消失。

我不太确定问题出在哪里......这是我的代码。希望不会太多。我拿出了不需要的东西。

App.component.html(角度的主要组件)

<div class="dropdown">
  <button *ngIf="loggedOff" class="btn" type="button" data-toggle="dropdown">Login
  </button>
  <ul *ngIf="loggedOff" class="dropdown-menu">
    <li>
      <button class="btn" id="loginButton" type="button" (click)="submit(username.value, pword.value)">
        Go!
      </button>
    </li>

  </ul>

应用组件.ts

export class AppComponent {
  loggedin: boolean;
  loggedOff: boolean;

  ngOnInit() {
    this.loggedin = false;
    this.loggedOff = true;
  }
  constructor(private loginService: LoginService,) { }

  submit(username: string, pword: string)
  {
    this.loggedin = this.loginService.signIn(username, pword);
    if(this.loggedin == true)
    {
      this.loggedOff = false;
    }
  }

登录服务.ts

  signIn(username: string, pword: string) : boolean
  {
    let sendData = new FormData();

    this.http.post(this.loginURL, sendData, {responseType: 'text'}).subscribe(res => {
      if(res.includes("Good")){
        this.loginAttempt = true;
      }else
        this.loginAttempt = false;
    });
    return this.loginAttempt;
  }

我在想它可能因为 Http 调用而有事可做?但是,我不太确定……我认为我描述的整个过程是同步的……也许不是?

标签: javascripthtmlangular

解决方案


正如有人已经指出的那样,Http 调用是异步的,因此您不能期望从您的服务返回的值会立即被填充。

相反,您必须从消费者那里异步订阅它,在这种情况下,消费者就是组件。像这样重构服务和组件就可以了:

// login.service.ts
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs';

@Injectable()
export class LoginService {
  private loginURL = 'http://...';

  constructor(private httpClient: HttpClient) { }

  signIn(username: string, password: string): Observable<string> {
    return this.httpClient.post(this.loginURL, { username, password }, { responseType: 'text' });
  }
}

// app.component.ts
export class AppComponent {
  isLoggedIn: boolean;

  constructor(private loginService: LoginService) { }

  submit(username: string, password: string) {
    this.loginService.signIn(username, password).subscribe(res => {
      this.isLoggedIn = res.indexOf('Good' >= 0);
    });
  }
}

不要忘记相应地编辑模板!:)


推荐阅读