Ste*_*nen 11 observable rxjs angular
在我的Angular 2应用程序中,我有许多可观察和订阅.当然,当我离开页面时我应该取消订阅,但我试图找出是否有可能获得有效订阅的数量.仅用于调试信息或忘记取消订阅时.
rxjs中是否有此类信息?
以下实用程序功能可能有助于...
function subscriberCount<T>(sourceObservable: Observable<T>, description: string) {
let counter = 0;
return new Observable((subscriber: Subscriber<T>) => {
const subscription = sourceObservable.subscribe(subscriber);
counter++;
console.log(`${description} subscriptions: ${counter}`);
return () => {
subscription.unsubscribe();
counter--;
console.log(`${description} subscriptions: ${counter}`);
}
});
}
Run Code Online (Sandbox Code Playgroud)
像这样使用它:
const timer$ = subscriberCount(Observable.timer(1000), 'Timer');
Run Code Online (Sandbox Code Playgroud)
每当订阅者数量发生变化时,控制台都会记录
可能有些晚,但是您可以利用的帮助rxjs-spy
。
此解决方案与建议的解决方案等效,并且在我看来,更好的维护性。
通常,我会在main.ts中将其全局启用,将其作为一种即发即弃策略。您只需要:
import { create } from 'rxjs-spy';
在角度初始化代码段之后立即在调试版本中初始化rxjs-spy:
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();
}
Run Code Online (Sandbox Code Playgroud)给您的观测对象起一个名字:
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"));
}
Run Code Online (Sandbox Code Playgroud)当您需要查看rxjs状态时,只需打开控制台窗口并使用rxSpy.show()
以获取当前快照
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)
归档时间: |
|
查看次数: |
5267 次 |
最近记录: |