How can i stop another request while there is still a request that is running. For example when i click a "submit" button and while it is still loading, how can i prevent users from saving duplicate transaction? Like when i keep clicking the "Enter" button. It duplicates the entry. What i want to do is, i want to stop another request for like 5 seconds while there is still a request ongoing. Here's my interceptor below.
@Injectable()
export class AuthInterceptor implements HttpInterceptor {
private authService: AuthService;
constructor(private injector: Injector, private router: Router) {}
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
this.authService = this.injector.get(AuthService);
const token = this.authService.getToken();
if (token) {
req = req.clone({ headers: req.headers.set('Authorization', 'Bearer ' + token) });
}
if (!req.headers.has('Content-Type')) {
req = req.clone({ headers: req.headers.set('Content-Type', 'application/json') });
}
req = req.clone({ headers: req.headers.set('Accept', 'application/json') });
return next.handle(req).do(
(event: HttpEvent<any>) => {},
(err: any) => {
if (err instanceof HttpErrorResponse) {
if (err.status === 401 || err.status === 403) {
}
}
}
)
.catch((error: HttpErrorResponse) => {
const parsedError = Object.assign({}, error, { error: JSON.parse(error.error) });
return Observable.throw(new HttpErrorResponse(parsedError));
});
}
}
In my case, I have handled it using loading component which show loading spinning images while http requests. Also, in order to prevent double click, you can set form buttons to be disable (and enable later) if you need.
This is a simple logic I thought :
app.component.html
<ng4-loading-spinner></ng4-loading-spinner> //to insert spinner
<router-outlet></router-outlet>
<app-footer></app-footer>
auth.service.ts (or you can use this in component.ts as well)
public login(auth){
this.spinnerService.show();
this.loginAuth(auth).subscribe(
result => {
this.spinnerService.hide();
console.log("loginAuth result : ",result);
//something for success
},
error => {
this.spinnerService.hide();
console.log("authService login error : ",error);
},
()=> {
console.log("authService login completed");
}
);
}
button control
component.html
<form ...>
...
<button type="submit" class="btn btn-primary" [disabled]="!getSubmitButton()">Submit</button>
...
</form>
component.ts
setSubmitButton(flag: boolean){
this.submitButtonStatus = flag;
}
getSubmitButton(){
return this.submitButtonStatus;
}
submit(){
//set button disable to prevent double click
this.setSubmitButton(false);
this.service.createSomething(newOne).subscribe(
res => {
console.log("created : ", res);
},
error => {
console.error("Error");
return Observable.throw(error);
},
() => {
console.log("Complete.");
this.setSubmitButton(true);
});