Angular2如何清空可观察流

时间:2016-02-27 20:47:48

标签: http typescript angular observable

我使用的是Angular 2.0.0-beta.0和TypeScript 1.7.5

当您在搜索框中键入内容并在屏幕上找到并显示某些内容时,您将删除搜索输入框,并且您希望显示一个空列表。它使用这段代码工作: 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");
        }
    }
}

1 个答案:

答案 0 :(得分:6)

在调用服务之前,您可以检查值是否为空:

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);
}