问题出现场景
因为接口请求过慢,会出现改变请求参数重新调用接口后,数据被前一次的请求结果覆盖:
举例:
输入框变化时请求数据,输入框输入 search 接口请求顺序:
接口请求1:参数s
接口请求2:参数se
接口请求3:参数sea
...
但是由于接口的快慢不同,先请求的接口可能时间更长,所以接口返回结果的顺序可能为:
接口2
接口3
接口1
接口最后获取的结果就不准确了
适用场景
input框输入
select框选择
tab切换
路由切换
......
解决方式
使用**switchMap**和**takeUntil**实现接口防抖操作。
实现效果为:多次请求时切断上一次请求,保留最新一次请求。
具体代码如下:
import { Component, OnChanges, OnInit, SimpleChanges } from '@angular/core';
import { apiService} from './../test.service';
import { Subject } from 'rxjs';
import { switchMap, takeUntil } from 'rxjs/operators';
@Component({
selector: 'app-testComponent',
templateUrl: './testComponent.component.html',
styleUrls: ['./testComponent.component.less']
})
export class testComponent implements OnInit, OnChanges {
searchTrigger$ = new Subject();
unsubscribe$ = new Subject();
constructor(
private api: apiService,
) {
}
ngOnInit(): void {
this.searchTrigger$.pipe(
switchMap((params) => this.api.getList(params)),
takeUntil(this.unsubscribe$),
).subscribe((res: any) => {
console.log(res);
}, err => {
console.log(err);
});
}
ngOnChanges(changes: SimpleChanges): void {
const params = {
...
}
this.searchTrigger$.next(params);
}
}