2017-07-26 51 views
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)"> 

回答

1

你要訂閱觀察的,如果你不同意,沒有任何反應。

編輯:

還有的地方,你可以聲明,並在視圖中觀察到的,通過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> 

更多關於asynchere

+0

我同意你的看法。但在教程中:https://angular.io/tutorial/toh-pt6#add-the-ability-to-search-by-name我沒有找到我們訂閱Observable的地方..你能告訴我如何? – Kael

+0

我會更新我的答案 –

+0

你救了我,謝謝:)所以在我沒有HTML模板的情況下* | async *,我必須在.switchMap&.catch之間添加.subscribe(//做些什麼)。是嗎? – Kael