简体   繁体   English

使用Angular 4取消http请求

[英]Cancel http request with Angular 4

How can I actually cancel request after subscribe() in Angular app??? 在Angular应用程序中subscription subscribe()之后,如何才能实际取消请求?

As usual, I use unsubscribe() or takeUntil() for cancelling my requests like this . 和往常一样,我使用unsubscribe()takeUntil()取消这样的请求。

But I have no idea why it's not working in this case: 但我不知道为什么在这种情况下不起作用:

userSubscription$: Subscription;

loadUser(userId: number) {
  // Cancel request
  if(this.userSubscription$) { this.userSubscription$.unsubscribe(); }

  // Load user
  this.userSubscription$ = this.userService.getUser(userId).subscribe((user: User) => {
     // ...
  });
}

And getUser in Service with Http: 并在Http中使用getUser:

getUser() {
  const url = '...';
  return this.http.get(url)
}

I tried with normal solutions but it only cancels Observable (means it didn't do anything after loading but requests are still loading => Make my site is slowly). 我尝试使用常规解决方案,但它只会取消Observable (意味着加载后它什么也没做,但是请求仍在加载=>使我的网站运行缓慢)。

Any idea why this happens? 知道为什么会这样吗?

For more information, I'm using: 有关更多信息,我正在使用:

  • Angular 4.0.0 角4.0.0
  • Using HttpModule for sending request (not HttpClientModule) 使用HttpModule发送请求(不是HttpClientModule)

Thanks for helping me! 感谢您的帮助!

Once an HTTP request has returned you the response and you want to unsubscribe the best idea is to use the take operator, try this: HTTP请求返回响应后,您想取消订阅的最佳方法是使用take运算符,请尝试以下操作:

this.userService.getUser(userId).take(1) subscribe((user: User) => {
     // ...
  });

Import the take operator from rxjs depending on your angular version. 根据您的角度版本从rxjs导入take运算符。

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

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