我想在Angular Tutorial中实现搜索组件。
问题:
search
方法会触发并修改searchTerms: Subject<string>
,但switchMap
永远不会触发。
代码:
进口
import { Component, OnInit } from '@angular/core';
import { SearchService } from "./search.service";
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 {Suggest} from "./suggest";
装饰
@Component({
selector: 'search-engine',
templateUrl: 'search-engine.component.html'
})
组件
export class SearchEngineComponent implements OnInit {
suggestions: Observable<Suggest[]>;
private searchTerms = new Subject<string>();
constructor(private searchService: SearchService) { }
ngOnInit(): void {
this.suggestions = this.searchTerms
.debounceTime(300)
.distinctUntilChanged()
.switchMap(term => {
console.log(term);
return Observable.of<Suggest[]>([]);
})
.catch(error => {
console.log(error);
return Observable.of<Suggest[]>([]);
});
}
search(term: string): void {
this.searchTerms.next(term);
}
}
HTML
<input #searchBox id="search-box" (keyup)="search(searchBox.value)">
答案 0 :(得分:2)
您必须订阅Observable,如果您没有订阅,则不会发生任何事情。
修改强>
还有另一种情况,你可以在视图中声明和观察,并通过async
管道隐式订阅,这就是这里发生的事情:
<div id="search-component">
<h4>Hero Search</h4>
<input #searchBox id="search-box" (keyup)="search(searchBox.value)" />
<div>
<div *ngFor="let hero of heroes | async"
(click)="gotoDetail(hero)" class="search-result" >
{{hero.name}}
</div>
</div>
</div>
有关async
管道here