【发布时间】:2017-11-15 06:38:49
【问题描述】:
如何更改 Angular 2 Tour of Heroes 搜索组件 (https://angular.io/generated/live-examples/toh-pt6/eplnkr.html),以便它在初始化时带来所有项目(在页面加载时显示所有英雄),并且当提供过滤器时,它会向服务发出新请求过滤后的结果放入 heros 变量中?
import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';
import { Observable } from 'rxjs/Observable';
import { Subject } from 'rxjs/Subject';
// Observable class extensions
import 'rxjs/add/observable/of';
// Observable operators
import 'rxjs/add/operator/catch';
import 'rxjs/add/operator/debounceTime';
import 'rxjs/add/operator/distinctUntilChanged';
import { HeroSearchService } from './hero-search.service';
import { Hero } from './hero';
@Component({
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 300ms after each keystroke before considering the term
.distinctUntilChanged() // ignore if next search term is same as previous
.switchMap(term => term // switch to new observable each time the term changes
// return the http search observable
? this.heroSearchService.search(term)
// or the observable of empty heroes if there was no search term
: Observable.of<Hero[]>([]))
.catch(error => {
// TODO: add real error handling
console.log(error);
return Observable.of<Hero[]>([]);
});
}
gotoDetail(hero: Hero): void {
let link = ['/detail', hero.id];
this.router.navigate(link);
}
}
目前只是在提供搜索词后发送请求。
【问题讨论】:
-
所以你想查看所有英雄而不是顶级英雄,我说对了吗还是我误解了你的问题?
-
我不需要更改 Top Heroes 的行为,我只需要默认显示所有英雄的列表,当输入内容时,列表会被过滤。
-
我尝试在
ngOnInit()中添加对this.search("");的调用,但似乎没有任何反应(服务未执行)。
标签: angular