在 Angular 2/4 中停止另一个请求,同时仍然存在请求

Stop Another Request While Still Existing Request in Angular 2/4

如何在仍有一个请求 运行 时停止另一个请求。例如,当我点击一个 "submit" 按钮并且它仍在加载时,我如何防止用户保存重复的交易?就像我一直点击 "Enter" 按钮一样。它复制条目。我想要做的是,我想在仍有请求进行时停止另一个请求大约 5 秒。下面是我的拦截器。

@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));
        });
  }
}

就我而言,我使用加载组件处理了它,该组件显示在 http 请求时加载旋转图像。此外,为了防止双击,您可以根据需要将表单按钮设置为禁用(稍后启用)。

这是我认为的简单逻辑:

app.component.html

<ng4-loading-spinner></ng4-loading-spinner>  //to insert spinner
<router-outlet></router-outlet>
<app-footer></app-footer>

auth.service.ts(或者您也可以在 component.ts 中使用它)

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");
            }
        );
    }

按钮控制

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);
        });