사용자가 여러 번 제출하는 것을 어떻게 방지합니까? 현재 문제는 사용자가 제출을 여러 번 클릭하면 여러 사용자가 생성된다는 것입니다. 한 번만 생성하고 다른 사용자를 생성하기 전에 기다려야 합니다.
#html 코드
<button mat-flat-button color="primary" [disabled]="userStatus == 'USER_EXISTS_ON_CURRENT_ACCOUNT'" (click)="createUser()">Create
User</button>
#ts 코드
createUser() {
this.accountService.create(this.modelForm.value).pipe(
finalize(() => {
this.isInProgress = false;
})
).subscribe({next: (res) => { this.notificationService.showSuccess('User has been created successfully.');
this._router.navigate(['settings/user']);
},
error: (err) => {this.notificationService.showError('Something went wrong, Try again later.');
this.isInProgress = false;
},
complete: () => {
this.isInProgress = false;
},
});
}
귀하의 코드를 약간 업데이트했습니다.
1 - 템플릿에 사용자 버튼을 생성해야 합니다.
<button #createUserBtn mat-flat-button color="primary" [disabled]="userStatus == 'USER_EXISTS_ON_CURRENT_ACCOUNT'"> CreateUser </button>
2 - .ts 파일의 사용자 생성 버튼 액세스
@ViewChild('createUserBtn', {static:true}) button;
3 - clicks$
클릭 이벤트를 저장할 변수 생성
clicks$: Observable<any>;
4 - ngOnInit에서: clicks$
클릭 이벤트를 수신하도록 변수 초기화
this.clicks$ = fromEvent(this.button.nativeElement, 'click');
5 - ngOnInit에서: 모든 클릭 이벤트에서 즉, click$
이벤트를 exhaustMap에 전달합니다.
ExhaustMap의 장점은 첫 번째(외부 관찰 가능) 이벤트가 트리거되면 내부 관찰 가능이 완료될 때까지 이벤트(외부 관찰 가능) 수신을 중지한다는 것입니다.
따라서 우리의 경우 사용자가 버튼을 처음 클릭하면(이벤트), exhaustMap
API 호출이 완료될 때까지 버튼 클릭 이벤트 수신을 중지합니다 createUser()
. 이 API 호출 관찰 가능은 handleResponse()
메서드를 사용하여 처리합니다 .
ngOnInit() {
this.clicks$ = fromEvent(this.button.nativeElement, 'click');
const result$ = this.clicks$.pipe(
tap(x => console.log('clicked.')),
exhaustMap(ev => {
console.log(`processing API call`);
return this.createUser();
})
);
result$.subscribe(this.handleResponse());
}
사용자 API 호출 생성
createUser(): Observable<any> {
return this.accountService.create(this.modelForm.value).pipe(
finalize(() => (this.isInProgress = false))
);
}
응답을 처리하려면
handleResponse(): any {
return {
next: res => {
this.notificationService.showSuccess('User has been created successfully.');
this._router.navigate(['settings/user']);
},
error: err => {
this.notificationService.showError('Something went wrong, Try again later.');
this.isInProgress = false;
}
complete: () => this.isInProgress = false;
};
}
버튼에 액세스할 수 없는 경우 코드를 AfterViewInit
완전히 테스트하지 않았기 때문에 ngOnit 코드를 오류가 있으면 알려주세요 로 이동할 수 있습니다.
ngAfterViewInit(): void {
fromEvent(this.button.nativeElement, 'click')
.pipe(
tap(x => console.log('clicked.')),
exhaustMap(ev => {
console.log(`processing API call`);
return this.createUser();
})
)
.pipe(tap(x => console.log('Api call completed....')))
.subscribe(this.handleResponse());
}
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다