本文介绍了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

  1. install rxjs-spy via your package manager

在 main.ts 中导入对 create 函数的引用:import { create } from 'rxjs-spy';

import in main.ts the reference to the create function: import { create } from 'rxjs-spy';

在 Angular 初始化片段之后立即在调试版本中初始化 rxjs-spy:

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();
}

  • 给你的 observable 起一个名字:

  • 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() 来获取当前快照

    您可以使用其他命令.一个非常详细的教程使用 rxjs Spy 进行调试(截至 2020 年,链接已失效).另一个不错的教程是使用 RxJS 进行工具.

    You may use additional commands. A very detailed tutorial was Debugging with rxjs Spy (the link is dead as of 2020). Another good tutorial is Tooling with RxJS.

    (如果有人阅读此答案设法修复格式,我会很高兴,因为我无法将其正确放入列表中)

    (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 可观察订阅数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

  • 08-19 14:41