如何在angular/typescript中使用两个搜索词发出api url请求
我正在制作一个mapquest api应用程序。我有两个输入框,一个用于“发件人”,另一个用于“收件人”,用于导航。通过在my app.component中硬编码这些值,它将正确返回json。然而,我不知道如何使用我正在使用的方法将这两个不同的搜索框放到我的管道中。 以下是我在html中的输入框:如何在angular/typescript中使用两个搜索词发出api url请求,angular,typescript,search,input,rxjs,Angular,Typescript,Search,Input,Rxjs,我正在制作一个mapquest api应用程序。我有两个输入框,一个用于“发件人”,另一个用于“收件人”,用于导航。通过在my app.component中硬编码这些值,它将正确返回json。然而,我不知道如何使用我正在使用的方法将这两个不同的搜索框放到我的管道中。 以下是我在html中的输入框: <form > <input #from id="from" (keyup)="search(from.value)"/>
<form >
<input #from id="from"
(keyup)="search(from.value)"/>
<input #to id="to"
(keyup)="search2(to.value)"/>
</form>
这是我的打字稿:
export class AppComponent implements OnInit {
title = 'hw5-part1';
mapResult: any;
to: string = 'boston';
from: string = 'poughkeepsie';
private searchTerms: Subject<string>;
any help would be super appreciable.
constructor(private mapQuestService: MapQuestService) { }
search(term: string): void {
this.searchTerms.next(term); }
ngOnInit() {
this.searchTerms = new Subject<string>();
this.searchTerms.pipe(
debounceTime(1000),
distinctUntilChanged(),
switchMap((x) => {
console.log('the term is ', x)
console.log(this.from, this.to);
return this.mapQuestService.getMap(this.from, this.to);
}))
.subscribe((result: any) => {
console.log(result);
this.mapResult = result.items;
console.log(result.route.legs[0].maneuvers);
});
}
}
导出类AppComponent实现OnInit{
标题='hw5-part1';
地图结果:任何;
to:string='boston';
from:string='poughkeepsie';
私人搜索术语:主题;
任何帮助都是非常可观的。
构造函数(私有mapQuestService:mapQuestService){}
搜索(术语:字符串):无效{
this.searchTerms.next(term);}
恩戈尼尼特(){
this.searchTerms=新主题();
这是“搜索术语”管道(
去BounceTime(1000),
distinctUntilChanged(),
开关映射((x)=>{
console.log('术语是',x)
console.log(this.from,this.to);
返回this.mapQuestService.getMap(this.from,this.to);
}))
.订阅((结果:任意)=>{
控制台日志(结果);
this.mapreult=result.items;
console.log(result.route.legs[0]。机动);
});
}
}
一种方法是在发送到switchMap()
时将两个值包装在一个对象中
并修改switchMap()
以使用这两个值
searchTerms$.pipe(
debounceTime(1000),
distinctUntilChanged((p, q) => p.from === q.from && p.to === q.to),
switchMap(input => {
let from = input.from;
let to = input.to;
if (from && to) {
return this.mapQuestService.getMap(from, to);
} else {
return of([]);
}
})
);
StackBlitz现场演示:
searchTerms$.pipe(
debounceTime(1000),
distinctUntilChanged((p, q) => p.from === q.from && p.to === q.to),
switchMap(input => {
let from = input.from;
let to = input.to;
if (from && to) {
return this.mapQuestService.getMap(from, to);
} else {
return of([]);
}
})
);