如何在我的应用Angular 9中限制API请求



这是我第一次尝试这样做,如果有人能指导,那将非常有帮助。我需要或我正在尝试的是,当你向API请求时,等待每个HTTP答案,直到你没有得到答案,你不能再点击按钮,但真的不知道如何启动

这是我调用对API执行POST方法的函数的代码

constructor(
private _builder:FormBuilder, private usersService: UsersService,private router: Router,
public _snackBar: MatSnackBar
) {}
sendUser(){
this.bSignIn = true;
let formData = new FormData();
formData.append('Identifier', this.loginForm.get('Identifier').value);
formData.append('Password', this.loginForm.get('Password').value);
setTimeout(() => {
this.usersService.validateUserCredentials(formData)
.subscribe(
res => {
this.bSignIn = false;
let auxRes: any = res;
if(auxRes.type == 'success'){
let auxUser = { 
userId: auxRes.id,
personId: auxRes.person_id,
clientId: auxRes.client_id,
projectId: auxRes.project_id
}
this.isSigned = true;
//this.usersService.validateSigned(auxRes);
localStorage.setItem('leadLogged', JSON.stringify(auxUser));
this.goToUsersDashboard(auxRes.id);
}
else{
this.openSnackBar(this.snackMessage);
this.loginForm.reset();
}
},
err => {
console.log("else");
window.alert('Introduce valid data');
}
)}, 4000);
}

ValidateUserCridentials是执行POST方法的函数

验证用户认证功能

validateUserCredentials(user: any){                              
return this.http.post(this.API_URL+'NONE-NONE-2/'+ENDPOINT_NAME+'/login/', user, this.httpOptions);
}

这是我的按钮

<button mat-raised-button [class.black]="!loginForm.invalid" [disabled]="loginForm.invalid" type="submit">Sign in</button>

它很简单,只需使用一些变量blockButton=false-当用户点击按钮时,在内部点击事件处理程序,一开始使用

if(this.blockButton) return;
this.blockButton=true;

因此,通过这种方式,只要blockButtontrue,就可以"阻止"单击处理程序(在"第一次单击"时(执行主代码。然后在.subscribe部分(当API返回响应时执行(中写入

this.blockButton=false

这将解锁你的按钮(只有当你从serwer得到响应时(

当您单击logIn按钮时,在typescript代码中禁用它,然后调用api。一旦得到结果,请再次启用它。

做一些像。。。

<button [disabled]="disabled" (click)="send()">Login</button>

代码背后:

async send(){
// disable the login button
this.disabled = true;
// using delay for http response
await this.delay(3000);
this.disabled = false;
}
private delay(ms: number){
return new Promise(resolve => setTimeout(resolve, ms));
}

disable是组件中的属性,单击它并发出API请求后,将其设置为true

快速演示-->https://stackblitz.com/edit/angular-qe11v1

您需要创建一个变量来跟踪禁用状态,然后在他们单击时将状态应用为true,并在订阅完成时将其返回为false。以下示例是根据Angular示例文档创建的:

相关代码:

组件.ts

disableConfig = false;
showConfig() {
this.configService.getConfig()
.subscribe(
(data: Config) => this.config = { ...data }, // success path
error => this.error = error, // error path
_ => this.disableConfig = false // on complete
);
}

component.html

<button [disabled]="disableConfig" (click)="clear(); disableConfig = true; showConfig()">get</button>

通过单击get按钮对以下stackblitz进行测试,了解它是如何在单击时禁用并在返回响应(或错误(时重新启用的。该代码包含在config文件夹中。

https://stackblitz.com/edit/angular-ycvjsz