Angular 2 Tour of Heroes検索コンポーネント(https://angular.io/generated/live-examples/toh-pt6/eplnkr.html)を変更すると、すべてのアイテムがinitに読み込まれますフィルタが提供されている場合、サービスに新しいリクエストを出し、フィルタ処理された結果をヒーロー変数に渡します。ユーザーがフィルタを追加する前に、すべてのアイテムをObservable にロードする必要があります。
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 **の動作を変更する必要はありません。デフォルトですべての英雄のリストを表示するだけで、何かが入力されると、リストがフィルタリングされます。 –
'ngOnInit()'の中で 'this.search(" ");'の呼び出しを追加しようとしましたが、何も起きていないようです(サービスは実行されません)。 –