javascript - 必须单击带有角度的单击事件两次才能完成操作
问题描述
我的按钮有问题。该按钮是一个登录按钮。当我在输入凭据后单击 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 调用而有事可做?但是,我不太确定……我认为我描述的整个过程是同步的……也许不是?
解决方案
正如有人已经指出的那样,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);
});
}
}
不要忘记相应地编辑模板!:)
推荐阅读
- rest - 如何在可完成的未来识别空指针异常?
- python - 每次有新文档时,我都需要帮助从文本文件中添加单词,同时在列表中创建新列表
- r - XML2-Package:如何处理空节点?
- php - 在 ACF 字段更新推送字段值到 WooCommerce 元值
- spring - Spring Data JPA 在不获取行 ById 的情况下更新行
- react-admin - 使用带有 RadioButtonGroupInput 的 ReferenceInput 时的反应警告
- javascript - node的bodyParser和express的urlencoded中间件有什么区别?
- reactjs - 如何使用接口在 Flow 中键入函数参数
- php - 路由模型绑定问题
- javascript - 将捕获的图像传递给 JavaScript 函数