Angular中tap操作符内设置的loading变量无法被*ngIf检测到的问题求助
Angular中tap操作符内设置的loading变量无法被*ngIf检测到的问题求助
大家好,我最近在做Angular的搜索自动补全功能时遇到了一个头疼的问题,想过来请教下各位!
我的需求是:当用户在搜索控件输入内容后,调用接口获取结果,在接口返回数据的过程中,自动补全的选项里要显示一个进度条提示加载状态。
下面是我写的TypeScript代码:
this.form.get("queryResult")!.valueChanges .pipe( debounceTime(800), // 每次按键后等待800ms再处理查询词 filter((value) => typeof value === 'string'), // 只处理字符串类型的输入值 tap((value) => { this.searchText = value; // 更新搜索文本 this.loading = value.length >= this.minSearchLength; }), filter((value) => value.length >= this.minSearchLength), // 只有当搜索词长度达到最小要求才继续 switchMap((value) => this.searchService.search(this.form.get('scope')?.value, value)) // 调用搜索服务 ) .subscribe((response) => { this.options = response; // 设置搜索结果 this.loading = false; // 获取结果后关闭加载状态 });
对应的HTML模板代码是:
<mat-autocomplete #auto="matAutocomplete" [displayWith]="displayFn" (optionSelected)="selectedItem = $event.option.value"> <mat-option *ngIf="loading" disabled> Loading... <mat-progress-bar mode="query"></mat-progress-bar> </mat-option> <ng-container *ngIf="!loading"> <mat-option *ngFor="let option of options" [value]="option" class="full-width"> <div> <strong>{{option.name}}</strong> <p>{{option.code}}</p> </div> </mat-option> </ng-container> </mat-autocomplete>
现在的问题是:当我在tap操作符里把loading设为true的时候,模板里的*ngIf完全检测不到这个值的变化,加载状态根本不显示;但在subscribe方法里把loading设为false的时候,模板却能正常响应,加载状态会消失。
我有点困惑,是不是tap操作符本身有什么特殊的地方,导致Angular的变更检测没触发呢?有没有大佬能帮忙解释下原因,或者给个解决办法呀?
备注:内容来源于stack exchange,提问作者VegDork
相关产品推荐
相关产品推荐

