我有一个搜索组件。它有一个模板,基本上就是一个输入字段和一个按钮。在提交时,我要求它从我的API加载数据。此数据需要显示在我的搜索结果组件中。
我的搜索组件如下所示:
search(f) {
this.router.navigate(['/item/search/' + f.value.itemSearch]);
}此路由呈现搜索结果组件。这样做的好处是,用户可以手动更改URL以搜索他们想要的内容/item/ search /任何内容。
搜索结果组件中的代码:
ngOnInit() {
this.subscription = this.route.params
.switchMap(params => {
this.postcode = params['item'] || '';
return this.service.search(this.item);
})
.subscribe(
items => this.items = items
);}
我遇到的问题是,无论何时完成搜索,它都会返回404/400之类的值,正确地显示没有找到任何数据。但是,使用搜索组件的后续搜索不会执行任何操作。我可以重新输入数据,然后重新点击submit,URL会发生变化,但不会再次执行搜索。有什么想法吗?
希望这一切都有意义:-/
添加:
search(item: string): Observable<any> {
const search = new URLSearchParams();
search.set('item', item);
return this.http.get(this._apiUrl, { search })
.map(response => response.json())
.catch(this.handleError);
}发布于 2017-12-20 00:56:32
假设您的handleError方法实际上并不处理错误,而是在处理错误时传播错误
this.subscription = this.route.params
.switchMap(params => {
this.postcode = params['item'] || '';
return this.service.search(this.item);
})
.subscribe(
items => this.items = items
);如果搜索对象发出错误,则整个可观察管道停止,并停留在其终端错误状态。因此,无论params observable发出什么都无关紧要:事件将不再被接收。
您需要通过返回一个不可观察到的错误来实际处理错误。就像这样
this.subscription = this.route.params
.switchMap(params => {
this.postcode = params['item'] || '';
return this.service.search(this.item).catch(() -> {
// display no result somehow
return Observable.empty());
});
})
.subscribe(
items => this.items = items
);https://stackoverflow.com/questions/47890851
复制相似问题