我试图在Tour of Heroes angular 2中的搜索组件中添加div,因此,当搜索组件解析请求时,会出现三个点。并且,一旦解决了observable,就会显示结果,或者,如果没有结果,则会显示未找到的消息。
到目前为止,我有这个:
<div id="search-component">
<h4>Hero Search</h4>
<input #searchBox id="search-box" (keyup)="search(searchBox.value)" />
<div>
<div *ngIf="searchBox.value.length > 0 && !(heroes | async)" >...</div>
<div *ngFor="let hero of heroes | async"
(click)="gotoDetail(hero)" class="search-result" >
{{hero.name}}
</div>
</div>
</div>
如果你能看到,我添加了以下div
<div *ngIf="searchBox.value.length > 0 && !(teams | async)" >...</div>
当搜索框不为空时以及团队尚未解决时,尝试使三个点出现。
但它不能很好地工作,因为如果我尝试搜索某些东西,同时请求已经完成,我可以看到三个点但是,一旦解决,如果我删除了一些字母再试一次,三个点不再出现了。
这是控制器,它与您在英雄中找到的完全相同(https://angular.io/docs/ts/latest/tutorial/toh-pt6.html)
import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';
import { Observable } from 'rxjs/Observable';
import { Subject } from 'rxjs/Subject';
import { HeroSearchService } from './hero-search.service';
import { Hero } from './hero';
@Component({
moduleId: module.id,
selector: 'hero-search',
templateUrl: 'hero-search.component.html',
styleUrls: [ 'hero-search.component.css' ],
providers: [HeroSearchService]
})
export class HeroSearchComponent implements OnInit {
heroes: Observable<Hero[]>;
private searchTerms = new Subject<string>();
constructor(
private heroSearchService: HeroSearchService,
private router: Router) {}
// Push a search term into the observable stream.
search(term: string): void {
this.searchTerms.next(term);
}
ngOnInit(): void {
this.heroes = this.searchTerms
.debounceTime(300) // wait for 300ms pause in events
.distinctUntilChanged() // ignore if next search term is same as previous
.switchMap(term => term // switch to new observable each time
// return the http search observable
? this.heroSearchService.search(term)
// or the observable of empty heroes if no search term
: Observable.of<Hero[]>([]))
.catch(error => {
// TODO: real error handling
console.log(error);
return Observable.of<Hero[]>([]);
});
}
gotoDetail(hero: Hero): void {
let link = ['/detail', hero.id];
this.router.navigate(link);
}
}
你知道我怎样才能改善这种状况?
答案 0 :(得分:1)
在你的条件下:
<div *ngIf="searchBox.value.length > 0 && !(heroes | async)" >...</div>
当搜索没有返回结果时你清空数组 但是英雄空数组返回true
所以你可以将英雄设置为null或undefined
或者检查长度,所以试试
<div *ngIf="searchBox.value.length > 0 && !((heroes&& heroes.length>0) | async)" >...</div>