2016-02-27 70 views
2

我採用了棱角分明2.0.0 beta.0和打字稿1.7.5Angular2如何清空觀察到流

當您在搜索框的東西,東西被發現,顯示在屏幕上,然後你刪除搜索輸入框,你想顯示一個空的列表。它使用這段代碼: this.searchTermStream.next("makesureyoudontfindanything");

有沒有人有更好的清潔解決方案,而不做一個http請求?

@Component({ 
    selector: 'contact-search', 
    template: ` 
     <div class="container"> 
      <div class="form-group"> 
       <label for="inputUser">Search</label> 
       <input #inputUser (keyup)="search(inputUser.value)"> 
      </div> 
      <ul> 
       <li *ngFor="#contact of contactList | async">{{contact.name}}</li> 
      </ul> 
     </div> 
    ` 
}) 

export class ContactSearch { 

    private searchTermStream = new Subject<string>(); 

    private contactList: Observable<Contact[]> = this.searchTermStream 
     .debounceTime(300) 
     .distinctUntilChanged() 
     .switchMap((value: string) => this.contactService.searchContacts(value)) 

    constructor(private contactService: ContactService) {} 

    search(value: string) { 
     if (value) { 
      this.searchTermStream.next(value); 
     } 
     else { 
      this.searchTermStream.next("makesureyoudontfindanything"); 
     } 
    } 
} 

回答

5

您可以檢查是否值是在調用服務之前空:

private contactList: Observable<Contact[]> = this.searchTermStream 
    .debounceTime(300) 
    .distinctUntilChanged() 
    .switchMap((value: string) => 
     0 < value.length ? this.contactService.searchContacts(value) : Observable.of([])) 

search(value: string) { 
    this.searchTermStream.next(value); 
} 
+0

不會刪除輸入時,只留下最後一個找到的值在contactList? – toskv

+1

@toskv你可能是對的..我會更新答案... – Sasxa

+0

不錯的解決方案,謝謝!!!! –