switchMap没有用下面的代码取消之前的请求


  • 当用户在自动完成文本框中输入值时,正在调用searchFunction。因此,这段代码应该做的是在用户输入的基础上将选项返回给自动完成下拉菜单,并且它应该只显示最后一个查询的选项。

  • 如果我使用这段代码,当它在其他地方调用时,它不返回任何东西(当我像上面一样使用主题和可观察对象时)。调用这个函数的地方应该是一个可观察对象,所以我们必须从这里返回一个可观察对象。此外,我不能编辑/更改调用上述函数的函数。

  • 为了只得到最后的结果,我需要switchMap。还有别的办法吗?

  • 下面的代码不工作。请建议是否需要更改

export class AppComponent {
readonly search = new ReplaySubject<string>(1);
searchResponse!: Observable<string[]>;
constructor(private http: HttpClient) {}
searchFunction = (query: string) => {
return (this.searchResponse = this.search.pipe(
debounceTime(300),
distinctUntilChanged(),
switchMap((query: string) => {
return this.http.searchData(query).pipe(
map((res: string[]) => {
return res.slice(0, 100);
})
);
})
));
};
}

问题是:

当用户在自动完成文本框中输入值时,正在调用searchFunction

每次调用函数时创建一个新的订阅。虽然模板应该取消订阅以前的订阅,但解决方案并不理想。

我会尝试这样做:

export class AppComponent {
readonly search = new Subject<string>();
readonly searchResponse: Observable<string[]>;
constructor(private http: HttpClient) {
this.searchResponse = this.search.pipe(
debounceTime(300),
distinctUntilChanged(),
switchMap((query: string) => {
return this.http.searchData(query).pipe(
map((res: string[]) => {
return res.slice(0, 100);
}),
// So we don't wreck the pipe. Import EMPTY from 'rxjs'
catchError(() => EMPTY)
);
})
}
searchFunction = (query: string) => {
this.search.next(query);
};
}

在这种情况下,您只订阅了一个搜索词。如果你正在使用反应式表单,你可以听听valueChanges

在本文中,您可以找到使用RxJS操作符的完整实现-请参阅"搜索类型- switchMap操作符示例"-希望能有所帮助!

https://blog.angular-university.io/rxjs-higher-order-mapping/

最新更新