我正在按照 Angular 2 的教程使用 HTTP 请求和 Observables 来搜索数据库。下面是具体教程的链接:https://angular.io/docs/ts/latest/tutorial/toh-pt6.html
您可以搜索“按名称搜索”来查找我所指的教程区域。
这是有问题的代码:
this.heroes = this.searchTerms
.debounceTime(300) // wait for 300ms pause in events
.distinctUntilChanged() // ignore if next search term is same as previous
.switchMap(term => term // switch to new observable each time
// return the http search observable
? this.heroSearchService.search(term)
// or the observable of empty heroes if no search term
: Observable.of<Hero[]>([]))
.catch(error => {
// TODO: real error handling
console.log(error);
return Observable.of<Hero[]>([]);
});
我能够对此代码进行适当的更改,以使其能够与我的应用程序一起使用,但我想知道当它成功返回数据以及当它无法找到您要查找的内容时如何调用函数。这可能相对简单,但我很难弄清楚它并且不太确定如何搜索它。
最佳答案
I am wondering how to invoke functions for when it successfully returns data and when it is unable to find what you're looking for
您仍然需要订阅。在您订阅之前不会发生任何事情。
this.searchTerms
.debounceTime(300)
.distinctUntilChanged()
.switchMap(term => term
? this.heroSearchService.search(term)
: Observable.of<Hero[]>([]))
.catch(error => {
return Observable.of<Hero[]>([]);
})
.subscribe(heroes => {
this.heroes = heroes;
doOtherStuff();
});
您可以在此处处理“成功”、“错误”和“完成”情况。订阅分别接受这三个回调。
.subscribe(
(heroes) => {}, // success
(error) => {}, // error
() => {} // completed/always
);
when it is unable to find what you're looking for
只需检查订阅“success”中的heroes
是否为空。
关于 Angular 2 : Using HTTP requests with Observables to search a database,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40477420/