If I inject a service 'Z' to component 'A' which spawns a dialog component 'B' which requires the service 'Z' to be a newly fresh copy of the service (provided in 'B' again). Will closing dialog 'B' "release" that nested service 'Z' so that component 'A' will see the original 'Z' service it provided before hand? Of course service 'Z' has a unique token used in both cases.

1

There are 1 best solutions below

1
On BEST ANSWER

Yes, you can, you just add service Z to the providers of component B (the dialog).

@Component({
  selector: 'app-b',
  template: `<!-- ... -->`,
  providers: [Z],
export class B {

  constructor(
    private myService: Z,
  ) {
    // init stuff
  }

}

The lifecycle of Z will be tied to B. There might be other instances of Z provided elsewhere, with different lifecycle, but the one provided by B will shadow the other instances, ie. B will get the instance coming from the provider from its own @Component. Note that this applies to B's child component, ie. this way the service Z is also shadowed for those by this instance.

To verify such situations (eg. what the lifecycle of things is, who gets which instance), I usually do the following

  • add logging to the constructor and ngOnDestroy of the items on question, eg. for B and Z in this case
  • in the service, add a static instance counter (so that it will be maintained across instances), increase that in the constructor, and save it into an instance field (so it becomes kind of an instance ID), and add the instance field to the lifecycle log statements

In this case, you would observe that possibly some instances of Z are created before the dialog B is instantiated, but more importantly a new one will be instantiated for B and also, it will be destroyed together with B.

Regarding this remark:

Of course service 'Z' has a unique token used in both cases.

You probably don't need that, you can use a single token, possibly Z itself. The injection token is only for finding the provider, doesn't directly influence the lifecycle. The lifecycle depends on where the provider is.