在我的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:
在角度初始化代码段之后立即在调试版本中初始化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(); }
给您的被观测者起一个名字:
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可观察的订阅数
发布评论