Angular 5 个基本搜索组件
Angular 5 basic search components
我有一个搜索组件。它有一个模板,基本上只是一个输入字段和一个按钮。在提交时,我要求它从我的 API 加载数据。此数据需要显示在我的搜索结果组件中。
我的搜索组件如下所示:
search(f) {
this.router.navigate(['/item/search/' + f.value.itemSearch]);
}
此路由呈现搜索结果组件。这样做的好处是用户可以手动更改 URL 以搜索他们想要的内容 /item/search/whatever.
搜索结果组件中的代码:
ngOnInit() {
this.subscription = this.route.params
.switchMap(params => {
this.postcode = params['item'] || '';
return this.service.search(this.item);
})
.subscribe(
items => this.items = items
);
}
我遇到的问题是,每当搜索完成并且 returns 一个 404/400 无论如何,它正确地显示没有找到数据。但是,使用搜索组件进行的后续搜索什么也不做。我可以重新输入数据并重新点击提交和 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);
}
假设您的 handleError 方法实际上并不处理错误,而是在执行时传播错误
this.subscription = this.route.params
.switchMap(params => {
this.postcode = params['item'] || '';
return this.service.search(this.item);
})
.subscribe(
items => this.items = items
);
如果搜索 observable 发出错误,则整个 observable 管道将停止,并停留在其最终错误状态。因此,无论 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
);
我有一个搜索组件。它有一个模板,基本上只是一个输入字段和一个按钮。在提交时,我要求它从我的 API 加载数据。此数据需要显示在我的搜索结果组件中。
我的搜索组件如下所示:
search(f) {
this.router.navigate(['/item/search/' + f.value.itemSearch]);
}
此路由呈现搜索结果组件。这样做的好处是用户可以手动更改 URL 以搜索他们想要的内容 /item/search/whatever.
搜索结果组件中的代码:
ngOnInit() {
this.subscription = this.route.params
.switchMap(params => {
this.postcode = params['item'] || '';
return this.service.search(this.item);
})
.subscribe(
items => this.items = items
);
}
我遇到的问题是,每当搜索完成并且 returns 一个 404/400 无论如何,它正确地显示没有找到数据。但是,使用搜索组件进行的后续搜索什么也不做。我可以重新输入数据并重新点击提交和 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);
}
假设您的 handleError 方法实际上并不处理错误,而是在执行时传播错误
this.subscription = this.route.params
.switchMap(params => {
this.postcode = params['item'] || '';
return this.service.search(this.item);
})
.subscribe(
items => this.items = items
);
如果搜索 observable 发出错误,则整个 observable 管道将停止,并停留在其最终错误状态。因此,无论 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
);