如果创建了新的后端请求,请取消以前的后端请求



我需要创建一个Angular组件,允许用户使用类型建议选择一个城市。

当用户键入三个或三个以上字符时,前端会要求后端提供一个以用户输入的名称开头的城市列表。

之后,我将城市列表的Observable传递到垫子选项组件

searchCities = (value: string): Observable<City[]> => {
if(value.length >= this.minCityNameLength){
return this.detailsITService.fetchCitiesByName(value);
}
return of([]);
};

如果使用新的用户输入调用方法searchCities(作为输入参数传递给我的自定义组件(,是否有方法"取消"请求?

Typeahead是一个非常常见的问题,rxjs是一个处理这个问题的好工具。假设input$是一个可观察的对象,发出用户输入的搜索字符串,您可以这样做:

input$.pipe(
// This is optional, just a suggestion. It prevents a
// request from being started while the user is still
// quickly typing a word. The value is a time in ms, see
// the operators docs for details.
debounceTime(250),
// Here's the actual piece of code: switchMap will
// start a new inner subscription whenever a new search
// input comes along, cancelling any still on-going previous
// request. This avoids any race conditions.
switchMap(input => input.length > this.minCityNameLength
? this.detailsITService.fetchCitiesByName(input)
: of([])
)
).subscribe(…);

例如,设置input$流的方式是使用

<input type="text" (input)="input$.next($event.target.value)" />

其中input$被定义为

public input$ = new Subject<string>();

你可以在这里找到一个工作示例。如果打开控制台并在有操作员和没有操作员的情况下进行尝试,您也可以看到debounceTime的效果。

最新更新