无法使用自定义角度指令禁用按钮

问题描述

我正在尝试在AJAX请求期间禁用按钮。

该流程有3个文件

  1. app.interceptor.ts isAjaxInProgress
  2. shared.service.ts
  3. disable-during-ajax.directive.ts

================================================ ===============

shared.service.ts:

private _isAnyRequestInProgress = new BehaviorSubject<boolean>(true);
isAnyRequestInProgress$ = this._isAnyRequestInProgress.asObservable();

app.interceptor.ts:

intercept(request: HttpRequest<any>,next: HttpHandler): Observable<HttpEvent<any>> {
this.sharedService.isAnyRequestInProgress = true;
// delay of few seconds
return next.handle(request).pipe(
      finalize(() => this.sharedService.isAnyRequestInProgress = false));
}

disable-during-ajax.directive.ts:

@Directive({
  selector: '[disableDuringAjax]',})

constructor(private el: ElementRef){}

ngOnInit(): void {
    this.sharedService.isAnyRequestInProgress$.subscribe(
      bool => this.el.nativeElement.disabled = bool
    );
  }

================================================ ===============

利用率:

<button type="submit" mat-flat-button color="primary" disableDuringAjax>Action</button>

也欢迎使用其他方法

解决方法

我很想直接进入Observable,而不使用指令。

组件:

buttonDisabled$: Observable<boolean>;

ngOnInit() {
  this.buttonDisabled$ = this.sharedService.isAnyRequestInProgress$;
}

模板:

<button type="submit" mat-flat-button color="primary" [disabled]="buttonDisabled$ | async">Action</button>