如何在 angular 路由更改时终止正在进行的 api 服务调用

How to terminate the inprogress api service call while angular route changes

在我的应用程序仪表板和多个页面中可用,仪表板页面调用多个 api 服务来获取报告,同时加载仪表板页面用户单击另一个页面 link,以便路由尽管正在执行与仪表板相关的 api 调用,但发生了变化。

是否有任何机制可以停止 angular 中的 api 服务调用。

喜欢jqueryxhr.abort()。

对于angular(不是angular JS), 您可以使用 unsubscribe 取消 API 呼叫。假设你正在使用订阅,你可以使用 Angular 生命周期钩子 ngOnDestroy 来取消请求。

ngOnDestroy() {

  this.subscription.unsubscribe();

}

您甚至可以向前移动并创建一个自定义装饰器,它允许您自动取消订阅所有订阅。这样就可以避免在 component.

中重复 ngOnDestroy

参考Automagically Unsubscribe in Angular

如果您的组件中有多个订阅,您可以考虑使用一个包来为您自动取消订阅,例如ngx-auto-unsubscribe.

// import auto unsubscribe library
import { AutoUnsubscribe } from "ngx-auto-unsubscribe";

@AutoUnsubscribe() // this decorator will handle automatically unsubscribing for your
@Component({
  selector: 'inbox'
})
export class InboxComponent {
  one: Subscription;
  two: Subscription; // etc.

  constructor( private store: Store<any>, private element : ElementRef ) {}

  ngOnInit() {
    this.one = store.select("data").subscribe(data => // do something);
    this.two = Observable.interval.subscribe(data => // do something);
  }

  // If you work with AOT this method must be present, even if empty! 
  // Otherwise 'ng build --prod' will optimize away any calls to ngOnDestroy, 
  // even if the method is added by the @AutoUnsubscribe decorator
  ngOnDestroy() {
    // You can also do whatever you need here
  }
}