Angular 5输入组件中的加载指示符被复制

时间:2018-02-19 02:54:36

标签: angular asynchronous rxjs font-awesome font-awesome-5

我想显示加载指示符,因为我的自动填充输入会从网络服务获取建议。

我有以下HTML:

<mat-form-field>
  <input type="text"
    placeholder="Enter a Suburb"
    matInput
    [formControl]="myControl"
    [matAutocomplete]="auto">

  <mat-autocomplete 
       autoActiveFirstOption 
       #auto="matAutocomplete" 
       [displayWith]="displayFn">
    <mat-option *ngFor="let item of suburbList" [value]="item">
      {{ item.value }}
    </mat-option>
  </mat-autocomplete>
</mat-form-field>
<i *ngIf="loading > 0" class="far fa-spinner fa-pulse"></i>

后面有以下TypeScript:

 loading = 0;
 myControl = new FormControl();
 suburbList: KeyValuePair<number, string>[] = [];

 constructor(private DataService: ListItemLookupService) {
    this.myControl.valueChanges
      .debounceTime(300)
      .distinctUntilChanged()
      .switchMap(
         value =>
         {
           if (value === null || value.length < 3) { return []; }
           this.loading = 1;
           return this.DataService.loadSuburbList(value);
         })
    .subscribe(data => {this.suburbList = data; this.loading = 0; },
               error => {this.loading = 0;},
               () => {this.loading = 0;}
       );
  }

所需的结果是显示和隐藏FontAwesome微调器。

实际发生的是,如果我相对快速地键入,则会创建并显示多个微调器。我认为这种情况正在发生,因为实际上有多个线程正在运行以从Web服务(this.DataService.loadSuburbList(value))获取数据。

我不想在这里制作单件服务,因为单个表单上可能有多个自动完成查找。我已经尝试过为此研究rxJs技术,并假设答案类似于C#委托。我不知道该如何从这里开始。

*注意:我将它设为计数器而不是bool,因此我可以跟踪为调试目的调用它的次数。我首先假设它必须与switchMap无法正常工作有关。

*编辑:在进一步测试时,这似乎是新FontAwesome包的错误。如果使用静态“正在加载...”字符串,它将按预期工作。

0 个答案:

没有答案