Avoiding circular dependencies with AngularJS Mediator pattern

1.1k views Asked by At

I have two services and a mediator. If I want the mediator to call AND be called by both services, I think that I need to make them dependencies of each other. This causes a circular dependency error.

Person Depends on Mediator to call Mediator methods

Mediator Depends on Person to call Person methods

Is the only solution to use events or promises? Am I implementing this pattern correctly?

2

There are 2 answers

3
Anton On BEST ANSWER

this is a bit of a problem that extends beyond angular and into javascript imho.

the standard way to structure mediators to avoid circular dependencies is to use interfaces, but javascript doesn't have interfaces.

in your situation, if you have the mediator injected into the service and vice versa, yes there will be an error.

assuming your mediator is also a service, a work around is not to have dependencies injected into the mediator, but rather have the mediator initialized before it is ever used with the 2 services that you need it to mediate for.

the alternative is not to use a mediator object, but use the publisher/subscriber pattern which is built into angular with $broadcast and $on. imho, this gives even looser coupling than the mediator pattern, so it has my thumbs up

0
SirTophamHatt On

Only your services which utilize Mediator should depend on Mediator. A service which publishes events injects Mediator. A service which subscribes to events injects Mediator and registers callbacks contained within the service. The Mediator should not depend on either service, it should only contain map a publishing events to a list of callback references.

See the Mediator in Angular example I wrote here