【问题标题】:How to cancel HttpRequests when changing a component更改组件时如何取消 HttpRequests
【发布时间】:2018-10-19 11:52:14
【问题描述】:

我正在开发一个 angular 5 的应用程序。

更改/销毁组件时,我需要停止所有 http 查询。

示例:我打开 ListUsersComponent,启动 httpquery 以获取用户列表,在该查询完成之前,我打开 ListAdminsComponent。所以在网络(浏览器)中,我有获取用户列表的查询仍在等待中。

我想在销毁 ListUsersComponent 时停止它。

当我更改组件时如何停止查询?

【问题讨论】:

    标签: angular httpclient angular5 angular-http-interceptors


    【解决方案1】:

    这就是解决方案:

    @Injectable()
    export class HttpCancelInterceptor implements HttpInterceptor {
      constructor(private httpCancelService: HttpCancelService) { }
    
      intercept<T>(req: HttpRequest<T>, next: HttpHandler): Observable<HttpEvent<T>> {
        return next.handle(req).takeUntil(this.httpCancelService.onCancelPendingRequests())
      }
    }
    

    取消服务

    @Injectable()
    export class HttpCancelService {
      private cancelPendingRequests$ = new Subject<void>()
    
      constructor() { }
    
      /** Cancels all pending Http requests. */
      public cancelPendingRequests() {
        this.cancelPendingRequests$.next()
      }
    
      public onCancelPendingRequests() {
        return this.cancelPendingRequests$.asObservable()
      }
    
    }
    

    链接: cancel

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-09-30
      • 1970-01-01
      • 2016-12-24
      • 1970-01-01
      • 2022-08-13
      • 2019-06-21
      相关资源
      最近更新 更多