订阅在Angular中取消订阅问题
我有一个Angular应用程序,其中包含大量事件挂钩,大量订阅等。
该应用在首次加载时功能正常,但是当我继续使用该应用程序时,它开始变得慢,实际上键入将有大约2到3秒。
我做的是我有一个订阅:subscription []
,然后将所有subscribe
s推向它,在ngondestroy
,i只需退缩
从所有订阅中。
对于事件,我使用fromevent
。
我有一些输入将挂钩到键>键
事件,有些输入不存在类型延迟问题,即使不存在键
挂钩。
export class Destroy {
static subscription(subscription: Subscription): void {
if (!subscription || subscription.closed) return;
subscription.unsubscribe();
subscription = null;
}
static subscriptions(subscriptions: Subscription[]): void {
if (!subscriptions) return;
subscriptions.forEach(item => {
if (!item) return;
Destroy.subscription(item);
});
}
}
@Component({...})
export class SomeComponent implements OnInit,OnDestroy{
subscriptions:Subscription[];
constructor(){
this.subscriptions = [];
}
ngOnInit(){
this.subscriptions.push(fromEvent('keydown',/*some inputs*/).subscribe(res=>{/**/}));
}
ngOnDestroy(){
Destroy.subscriptions(this.subscriptions);
}
}
这是我所能做的吗?我确实退订了所有订阅,但是为什么我的应用程序之后无法正常工作?
I have an angular app that contains lots of event hooks, a lot of subscriptions etc.
The app is functional at first load, but when I continue using the app, it starts to get slow and practically typing would have about 2 to 3 seconds delay.
What I've done is that I have a subscriptions: Subscription[]
and then push all the subscribe
s to it, in ngOnDestroy
, I just unsubscribe
from all the subscriptions.
for events I use fromEvent
.
I have some inputs that hook to keypress
event and some don't and all the inputs have type delay issue even if no keypress
hook exists.
export class Destroy {
static subscription(subscription: Subscription): void {
if (!subscription || subscription.closed) return;
subscription.unsubscribe();
subscription = null;
}
static subscriptions(subscriptions: Subscription[]): void {
if (!subscriptions) return;
subscriptions.forEach(item => {
if (!item) return;
Destroy.subscription(item);
});
}
}
@Component({...})
export class SomeComponent implements OnInit,OnDestroy{
subscriptions:Subscription[];
constructor(){
this.subscriptions = [];
}
ngOnInit(){
this.subscriptions.push(fromEvent('keydown',/*some inputs*/).subscribe(res=>{/**/}));
}
ngOnDestroy(){
Destroy.subscriptions(this.subscriptions);
}
}
Is this all I can do? I do unsubscribe from all the subscription, but why my app does not work properly after while?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
即使您
销毁
类似乎都应该工作。无论如何,要缩小问题,您应该添加2
console.log
:一旦添加了这些问题,您就可以查看所有订阅是否取消订阅,而且订阅仍然保留,您应该看到”键入事件“记录了多次。
至于
destoy
类,我会这样做:我从来没有这种方法有问题
Should work even if you
Destroy
class seems overcomplicated.anyway, to narrow down your problem you should add 2
console.log
:once you have added those, you can see if all your subscriptions get unsubscribed or not and also if the subscription remains, you should see "key down event" logged multiple times.
as for the
Destoy
class I would simply do it like this:I never had problems with this approach