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

时间:2018-03-21 03:31:05

标签: angular interceptor angular-http-interceptors angular-httpclient

如果仍有正在运行的请求,我该如何停止其他请求?例如,当我单击“提交”按钮并且仍在加载时,如何阻止用户保存重复的事务?就像我一直点击“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));
        });
  }
}

1 个答案:

答案 0 :(得分:0)

在我的情况下,我使用加载组件处理它,显示在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);
        });