Javascript 如何在订阅服务器中使用异步功能
我有一个输入框,它在valueChange上调用一个调用API的异步函数Javascript 如何在订阅服务器中使用异步功能,javascript,angular,typescript,asynchronous,Javascript,Angular,Typescript,Asynchronous,我有一个输入框,它在valueChange上调用一个调用API的异步函数 this.searchFrom = new FormGroup({ ss: new FormControl() }); this.searchFrom.valueChanges .pipe(debounceTime(500)) .pipe(distinctUntilChanged()) .subscribe((b) => { th
this.searchFrom = new FormGroup({
ss: new FormControl()
});
this.searchFrom.valueChanges
.pipe(debounceTime(500))
.pipe(distinctUntilChanged())
.subscribe((b) => {
this.search(b);
});
搜索(ss:string){
log(“您应该了解rxjs和it操作符
这里有一个可行的解决方案:
this.searchFrom=new FormGroup({
ss:new FormControl()
});
此.searchFrom.valueChanges
.烟斗(
去BounceTime(500),
distinctUntilChanged(),
switchMap(x=>this.search(x.ss))
).订阅((结果)=>{
//如果没有错误,则结果包含HTTP结果
});
搜索(ss:string){
console.log(“不知道你为什么要将你的可观察性转化为承诺,无论如何,我有另一种方法来解决你的问题
试试这个
您是否有任何错误?没有,我没有收到任何错误。您可以提供stackblitz吗?在开发人员控制台中,网络标记您的请求是否完成?您还需要一个映射运算符,这在您的解决方案中是缺失的。需要映射,但需要获取formControl:map的值(value=>value.ss)订阅上的this.searchFrom.valueChanges将返回一个我相信的事件对象,因此要获取输入的字符串,我们需要使用映射运算符yes gerome您是对的,请更新我的映射运算符
search(ss: string) {
console.log("You should learn about rxjs and it operators.
Here a working solution:
this.searchFrom = new FormGroup({
ss: new FormControl()
});
this.searchFrom.valueChanges
.pipe(
debounceTime(500),
distinctUntilChanged(),
switchMap(x => this.search(x.ss))
).subscribe((result) => {
// result contains HTTP-result if non Error
});
search(ss: string) {
console.log("Not sure why you are converting your observable into promise, anyway i have another approach to solve your problem,
Try this
this.searchFrom.valueChanges.pipe(
map(value => value.ss),
debounceTime(500),
distinctUntilChanged(),
switchMap(search => this.search(search))
).subscribe(data => console.log(data));
search(ss: string) {
return this.http.post(endpoint + 'search', { 'ss': ss })
}