Rxjs number of observable subscriptions

前端 未结 3 451
南方客
南方客 2021-01-01 14:47

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

3条回答
  •  隐瞒了意图╮
    2021-01-01 15:10

    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.

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

    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();
      }
      
      
    4. 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 {
          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(this.baseUrl + "api/product", { params: params }).pipe(tag("getProductById"));
      }
      
      
    5. when you need to look at rxjs state, you can simply open the console window and use rxSpy.show() to have the current snapshot

    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)

提交回复
热议问题