【发布时间】:2023-03-08 14:40:01
【问题描述】:
问题
我正在尝试在搜索服务忙于检索和过滤结果时显示微调器。我认为*ngIf 的较新 Angular 语法可以让您在 if 条件之外还有一个 else 条件。但是每当我开始输入时,微调器就会正确显示,然后控制台中的错误会在更改检测运行后抱怨值发生更改。
- 如何解决此问题?
- 对组件成员/属性的更改是否会反映在视图中?为什么更改检测不解决这个问题,而不是抱怨我的时间安排?
组件
@Component({
selector: 'app-help-search',
templateUrl: './help-search.component.html',
styleUrls: ['./help-search.component.scss'],
providers: [HelpSearchService]
})
export class HelpSearchComponent implements OnInit {
searching: boolean;
helpItems: Observable<HelpItem[]>;
private searchTerms = new Subject<string>();
constructor(
private alertService: AppLevelAlertService,
private helpSearchService: HelpSearchService,
private router: Router) { }
/**
* Push a search term into the observable stream.
*/
search(term: string): void {
this.searching = true;
this.searchTerms.next(term);
}
ngOnInit() {
this.helpItems = this.searchTerms
.debounceTime(300)
.distinctUntilChanged()
.switchMap(term => term
? this.helpSearchService.search(term)
: Observable.of<HelpItem[]>([])
)
.catch(error => {
this.alertService.errorOccurred.emit(new Error(error._body.error));
return Observable.of<HelpItem[]>([]);
})
.finally(() => this.searching = false);
}
gotoHelpItem(helpItem: HelpItem): void {
this.router.navigateByUrl(helpItem.url.toString());
}
}
组件模板
<div id="search-component">
<div class="form-group">
<label for="search-box">Search for help topics: </label>
<input type="text" #searchBox id="search-box" (keyup)="search(searchBox.value)" style="display: block; width: 100%; font-size: 20pt; height: 25pt" />
</div>
<div *ngIf="searching; then spinner else searchResults"></div>
<ng-template #spinner>
<span class="spinner spinner-lg">
Loading...
</span>
</ng-template>
<ng-template #searchResults>
<div *ngFor="let helpItem of helpItems | async" (click)="gotoHelpItem(helpItem)" class="search-result">
<app-help-item [helpItem]="helpItem"></app-help-item>
</div>
</ng-template>
</div>
我尝试过的
我注意到在.finally 谓词中将this.searching 设置为false 是导致此问题的原因。而不是这种方法,我尝试订阅this.helpItems 并在next 谓词设置this.searching 到false。当结果返回时,这会正确移除微调器。但不幸的是,这仍然不起作用,因为 for 循环没有取代微调器的位置。结果返回后,ng-templates 都会消失。
【问题讨论】:
-
您没有订阅数据。你想达到什么目的?
-
我正在尝试让帮助项目显示在视图中。如果我不包括微调器,它在视图中显示得很好。但我试图让微调器出现,直到呈现搜索结果。有意义吗?
标签: angular binding angular2-changedetection