在我的应用程序仪表板和多个页面可用,仪表板页面调用多个api服务来获取报告,在加载仪表板页面时,用户单击其他页面链接,以便通过仪表板相关的api调用正在执行路径更改。
是否有任何机制可以以角度停止api服务调用。
喜欢jquery xhr.abort()。
答案 0 :(得分:1)
如果您的组件中有多个订阅,您可以考虑使用一个处理自动取消订阅的包,例如: 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
}
}
答案 1 :(得分:0)
对于角度(非角度JS),
您可以使用unsubscribe
取消API调用。假设您正在使用订阅,则可以使用Angular生命周期挂钩ngOnDestroy
来取消请求。
ngOnDestroy() {
this.subscription.unsubscribe();
}
您甚至可以向前移动并创建一个自定义装饰器,允许您自动取消订阅所有订阅。因此,您可以避免在组件中重复ngOnDestroy
。