如何更改英雄搜索組件(https://angular.io/generated/live-examples/toh-pt6/eplnkr.html)的Angular 2 Tour of Heroes搜索組件(https://angular.io/generated/live-examples/toh-pt6/eplnkr.html),以便它將init上的所有項目(在頁面加載時顯示所有Heroes)過濾器提供它向服務獲取過濾結果到英雄變量的新請求?需要在用戶添加任何過濾器之前將所有項目加載到Observable <Hero[]>
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);
}
}
目前只是在提供搜索詞後發送請求。
所以,你想看到所有的英雄,而不是**熱門英雄**,我纔得到這個權利還是我誤解你的問題? – codtex
我不需要改變** Top Heroes **的行爲,我只需要在默認情況下顯示所有英雄列表,當輸入內容時,列表將被過濾。 –
我試着給'this.search(「」);''ngOnInit()'內部添加一個調用,但似乎沒有任何事情發生(服務未執行)。 –