Html 对http服务调用的解块输入
我目前正在做的是将输入双向绑定设置为Html 对http服务调用的解块输入,html,angular,typescript,Html,Angular,Typescript,我目前正在做的是将输入双向绑定设置为appRequestParams.appName,并且在每个keyup事件上,都会调用fetchApps()方法 我正在尝试对输入进行去盎司处理,这样它就不会立即在每个keyup上发出后端http请求 我已经阅读了关于如何去做这件事的方法,这里是我得出的结论 HTML <input #searchBox id="search" mdInput placeholder="Search by list of apps" (keyup)="search(sea
appRequestParams.appName
,并且在每个keyup事件上,都会调用fetchApps()
方法
我正在尝试对输入进行去盎司处理,这样它就不会立即在每个keyup上发出后端http请求
我已经阅读了关于如何去做这件事的方法,这里是我得出的结论
HTML
<input #searchBox id="search" mdInput placeholder="Search by list of apps" (keyup)="search(searchBox.value)" />
代码中与去盎司相关的部分很好。问题是,如果不返回另一个可观察对象,就无法调用switchMap SwitchMap基本上会将一个可观察对象最后发出的值转换为另一个可观察对象,从而提供自动取消动态http请求的额外能力 请尝试以下操作:
private searchTerms = new Subject<string>();
search(value: string): void {
this.searchTerms.next(value);
}
fetchApps() {
this.appService.query({
appName: this.appRequestParams.appName ? this.appRequestParams.appName : null,
});
}
ngOnInit() {
this.searchTerms
.debounceTime(300)
.distinctUntilChanged()
.switchMap((value: string) => {
this.appRequestParams.appName = value;
return this.fetchApps();
}).subscribe(
(res: ResponseWrapper) => this.onSuccess(res.json, res.headers),
(res: ResponseWrapper) => this.onError(res.json)
);
}
@Injectable()
export class FooService{
..
getFooById(id:string): Observable<FooInterface>{
return this.http.get('endpoint/${id}')
.map(res=>res.json())
.catch(_throw(error));
}
}
在处理http的过程中,如果现在导航到root/foo/1312313,前面的请求将自动取消
switchMap还有其他应用程序,但它需要对内部/外部观测值以及其中的一些内部内容有一些了解
您的解决方案效率低下,因为您订阅的是取消公告的输入值以及由它们触发的http响应,但您对第一个没有做任何处理,而实际上您只想订阅http响应。因此,您可以以正确的方式使用switchMap来保存其中一个订阅。我最终使用了这个,它工作得非常好
this.searchTerms
.debounceTime(300)
.distinctUntilChanged()
.switchMap(
(term) => {
console.log('Term:' + term);
this.appRequestParams.appName = term;
this.fetchApps();
return term;
})
.subscribe();
}
问题在于返回类型。请检查您的服务的返回类型在我的应用程序中并非真正的智能解决方案opinion@Jota.Toledo这是一个快速修复。我正在试图了解
开关映射
和可观察对象
现在是如何工作的。您的回答产生了相同的错误,因此进行了此修复。也许您可以解释一下为什么这不理想?因此,虽然此解决方案确实解决了问题,但它不会在每个keyup问题上立即触发后端http请求,它不能通过取消以前的“正在运行”请求来确保请求响应按顺序返回?完美。fetchApps()
方法下需要进行细微更改。需要返回此.appService.query
@Injectable()
export class FooService{
..
getFooById(id:string): Observable<FooInterface>{
return this.http.get('endpoint/${id}')
.map(res=>res.json())
.catch(_throw(error));
}
}
@Component({...})
class FooPreviewComponent{
data: FooInterface;
constructor(
private _route: ActivatedRoute,
private _service: FooService) {
this._route.params
.switchMap(params=>
this._service.getFooById(params.id))//switchMap return type is Observable<FooInterface> because of the definition of getFooById
.subscribe(fooElement => this.data); //intellisense will detect the type of fooElement as FooInterface because of the return type of switchmap
}
}
this.searchTerms
.debounceTime(300)
.distinctUntilChanged()
.switchMap(
(term) => {
console.log('Term:' + term);
this.appRequestParams.appName = term;
this.fetchApps();
return term;
})
.subscribe();
}