0
我想要在Angular Tutorial中實現搜索組件。關於可觀察的永不觸發的角度switchMap
問題:
的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)">
我同意你的看法。但在教程中:https://angular.io/tutorial/toh-pt6#add-the-ability-to-search-by-name我沒有找到我們訂閱Observable的地方..你能告訴我如何? – Kael
我會更新我的答案 –
你救了我,謝謝:)所以在我沒有HTML模板的情況下* | async *,我必須在.switchMap&.catch之間添加.subscribe(//做些什麼)。是嗎? – Kael