angular - How to know if component is currently the loaded component in router-outlet -


i have application lazy loaded modules.

in 1 specific lazy loaded module, have parent component, has router-outlet.

in parent component have button emit event using shared service (provided on lazy loaded module).

each child component (which loaded in router-outlet) subscribing event using same shared service!

i tried recreate use case in following plunkr using heroes demo.

open dev tools see console messages.

  • click on heroes link (it should selected default).
  • click on hero item list.
  • click on admin link.
  • click on emit test button (upper right nav)

you'll see -in console- event received both components, both components should not 'active' !!!

1) design?

2) how know if current component active one?


summary/update

from understanding, eventemitter/subject can subscribed many times, when unsubscribed cannot use it/subscribe afaik.

my solution was:

1) in service ended doing folowing:

get(){   if (!this.testevent.closed) {       this.testevent.complete();       this.testevent.unsubscribe();     }     this.testevent= new eventemitter<void>();     return this.testevent;   } } 

2) in each component subscribe event, added ngdestroy , unsubscribed event:

  ngondestroy() {     this.testevent.unsubscribe();   } 

you have service, singleton. service exists beginning of application until end.

you have 2 components. these not singletons. created when must displayed on page, , destroyed when must not anymore.

and, when components created, subscribe observable inside singleton service. mean? means observable needs keep reference observer, has emplicit reference (this) component instance. without reference, observable wouldn't able call observer when event emitted. so, though angular doesn't need component instance anymore, observable still has reference it, , calls when event emitted.

you need unsubscribe when component not needed anymore:

private subscription: subscription;  ngoninit() {     this.subscription = this.service.gettestevent().subscribe(...); }  ngondestroy() {     this.subscription.unsubscribe(); } 

without doing that, not have observers called nothing, making app slower, have memory leak.


Comments

Popular posts from this blog

java - SSE Emitter : Manage timeouts and complete() -

jquery - uncaught exception: DataTables Editor - remote hosting of code not allowed -

java - How to resolve error - package com.squareup.okhttp3 doesn't exist? -