Her*_*sen 2 http observable typescript angular
我使用的是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");
}
}
}
Run Code Online (Sandbox Code Playgroud)
在调用服务之前,您可以检查值是否为空:
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);
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2853 次 |
| 最近记录: |