简体   繁体   English

如何在 Angular 2 的服务中取消预览未完成的相同类型的 HTTP 请求?

[英]How to cancel previews incomplete HTTP requests of the same type in a service in Angular 2?

I'm using Angular 9 in my web app.我在我的网络应用程序中使用 Angular 9。 I'm using a lot of services to connect to a web service.我正在使用很多服务来连接到 Web 服务。 Sometimes a lot of identical requests are sent to a service.有时,许多相同的请求被发送到一个服务。 Maybe when a user click on a button repeatedly.也许当用户反复单击按钮时。

I want to cancel previews incomplete requests for all of my services.我想取消对我所有服务的预览不完整请求。 What's the best solution?最好的解决办法是什么? (Maybe using RXJS) (也许使用 RXJS)

This is one of my service functions:这是我的服务功能之一:

constructor(private http: HttpClient) {}

getList(options?: ApiListOptions) {
  return this.http.post<ApiResponse<UserGet[]>>(
    environment.apiRoot + 'user/list',
    options,
    { headers: this.headers() }
  );
}

Thanks谢谢

Please try below with takeUntil rxjs operator you will be able to do the same.请在下面尝试使用 takeUntil rxjs 运算符,您将能够执行相同的操作。

export class YourComponent {
   protected ngUnsubscribe: Subject<void> = new Subject<void>();

   [...]

   public httpGet(): void {
      this.http.get()
         .takeUntil(this.ngUnsubscribe)
         .subscribe( (data) => { ... })
   }

   public ngOnDestroy(): void {
       this.ngUnsubscribe.next();
       this.ngUnsubscribe.complete();
   }
}

For your specific case, like frequent button clicks, you can use switchMap() combine with debounceTime() to limit the frequency of action and http calls.针对您的特殊情况下,如频繁的点击按钮,你可以使用switchMap()有机结合起来debounceTime()来限制行动和HTTP调用的频率。 You can use Subject for action trigger instead of component method您可以使用Subject作为动作触发器而不是组件方法

<button click="getList.next()">click</button>

getList=new Subject()
getList.pipe(debounceTime(2000),switchMap(()=>
this.http.post<ApiResponse<UserGet[]>>(
    environment.apiRoot + 'user/list',
    options,
    { headers: this.headers() }
  );
)).subscribe()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM