我正在按照 Angular 教程构建一个简单的应用程序。当我在输入框中键入术语时,应用程序会向搜索用户发送 ajax。我对这里的 Observable 感到困惑。
(1)
如果搜索词短于 3 个单词,我想清除数据。我使用 Observable.of 返回一个空数组。
(2)
如果发生 http 错误,catch
block 中也会返回一个空数组。
但是,在这两种情况之一之后,流似乎“停止”了,因为我将 this.users
指向一个新的 Observable。我应该再次执行类似 this.users = new subject()
的操作吗?这里正确的做法是什么?
html:
<div class="wrapper">
<input #searchBox id="search-box" (keyup)="search(searchBox.value)" />
<div class="loader" [hidden]="!loading"></div>
</div>
获取用户服务:
//Sending ajax, return an Observable
组件:
export class searchComponent implements OnInit {
constructor(private getUserService: GetUserService) { }
private searchTerms = new Subject<string>();
users: Observable<User[]>;
loading: boolean = false;
search(term: string): void {
if(term.length >= 3) {
this.loading = true;
this.searchTerms.next(term);
} else {
//issue (1) occurs after this
this.users = Observable.of<User[]>([]);
}
}
ngOnInit(): void {
this.users = this.searchTerms
.debounceTime(400)
.distinctUntilChanged()
//service will not be called after (1) or (2) occurs
.switchMap(term => this.getUserService.getUser(term))
.map(data => {
this.loading = false;
return data;
})
.catch(error => {
//issue (2) occurs after this
this.loading = false;
return Observable.of<User[]>([]);
});
}
}
最佳答案
你没有在正确的地方做事。应该是这样
search(term: string) {
// emit systematically. The observable chain will just return
// 0 result if the term is too short
this.searchTerms.next(term);
}
ngOnInit() {
this.users = this.searchTerms
.debounceTime(400)
.distinctUntilChanged()
.switchMap(term => {
if (term.length < 3) {
return Observable.of([]);
}
else {
this.loading = true;
return this.getUserService.getUser(term)
// catch here to make sure that an http error doesn't break the chain
.catch(() => return Observable.of([])
.finally(() => this.loading = false);
}
});
}
关于Angular Observable 错误处理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45398447/