Rxjs可观察的订阅数 [英] Rxjs number of observable subscriptions

查看:154
本文介绍了Rxjs可观察的订阅数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的Angular 2应用程序中,我有很多可观察项和订阅项. 当然,离开页面时我应该退订,但我试图找出是否有可能获得活动订阅的数量. 仅用于调试信息或当我忘记退订时.

In my Angular 2 app i have many observables and subscriptions. Ofcourse I should unsubscribe when I leave the page, but i'm trying to find out if it's possible to get the number of active subscriptions. Just for debugging info or when i forget to unsubscribe.

rxjs中是否有可用的此类信息?

Is there such information available in rxjs?

推荐答案

可能有点晚,但是您可以利用 rxjs-spy .

Probably a bit late, but you could leverage the help of rxjs-spy.

此解决方案与建议的解决方案等效,并且在我看来,它具有更好的可维护性.

This solution is equivalent the proposed one, and, in my opinion, better maintainable.

我通常会在main.ts中全局启用它,将其作为一种即发即弃"策略.您只需要:

I usually enable it globally in main.ts as a fire and forget strategy. You simply have to:

  1. 通过您的软件包管理器安装rxjs-spy
  2. 在main.ts中导入对create函数的引用:import { create } from 'rxjs-spy';
  3. 在角度初始化代码段之后立即在调试版本中初始化rxjs-spy:

  1. install rxjs-spy via your package manager
  2. import in main.ts the reference to the create function: import { create } from 'rxjs-spy';
  3. initialize the rxjs-spy in debug builds right after the angular initialization snippet:


if (environment.production) {
    enableProdMode();
}
else {
    //we enable RXjs Spy on non production bulds only
    const spy = create();
    // we call show for two purposes: first is to log to the console an empty snapshot so we can see that everything is working as expected, then to suppress unused variable usage (the latter is a convention on mine)
    spy.show();
}

  • 给您的被观测者起一个名字:

  • give your observables a name:

    
    import { tag } from 'rxjs-spy/operators';
    
    ...
    
    // This is a sample method which asks for a "Product" entity. Product and this.http is omitted as the focus is on tagging the observable
    public getProductById(productId: number): Observable<Product> {
        let params = new HttpParams()
            .append('productId', productId.toString())
            ;
        // we tag the returned observable with the name 'getProductById' (this is a convention on mine, you can choose whatsoever name)
        return this.http.get<Product>(this.baseUrl + "api/product", { params: params }).pipe(tag("getProductById"));
    }
    
    

  • 当您需要查看rxjs状态时,只需打开控制台窗口并使用rxSpy.show()即可获取当前快照

  • when you need to look at rxjs state, you can simply open the console window and use rxSpy.show() to have the current snapshot

    您可以使用其他命令.一个非常详细的教程是使用rxjs Spy进行调试.

    You may use additional commands. A very detailed tutorial is Debugging with rxjs Spy.

    (如果有人阅读此答案后能够解决格式问题,我感到很高兴,因为我无法在列表中正确找到格式)

    (I'd be very glad if somebody reading this answer manages to fix the formatting as I cannot have it properly within the list)

    这篇关于Rxjs可观察的订阅数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

  • 查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆