Issue
In my Angular 2 app, I have two services that depend on each other (service A calling methods from service B and vice versa).
Here are the relevant code:
app.component.ts
:
import {Component} from 'angular2/core';
import {TempService} from '../services/tmp';
import {Temp2Service} from '../services/tmp2';
@Component({
selector: 'my-app',
templateUrl: 'app/app/app.component.html',
providers: [TempService, Temp2Service]
})
export class AppComponent { (...) }
Service 1:
import {Injectable} from 'angular2/core';
import {Temp2Service} from './tmp2';
@Injectable()
export class TempService {
constructor (private _sessionService: Temp2Service) {}
}
Service 2:
import {Injectable} from 'angular2/core';
import {TempService} from './tmp';
@Injectable()
export class Temp2Service {
constructor (private _sessionService: TempService) {}
}
Running the app leads to the following error:
EXCEPTION: Cannot resolve all parameters for 'Temp2Service'(undefined). Make sure that all the parameters are decorated with Inject or have valid type annotations and that 'Temp2Service' is decorated with Injectable
When commenting the constructor in one of the services, the app runs fine. So my guess is that the "cross-reference" of the two services is causing the problem.
Do you have an idea what is going wrong here? Or is my approach already wrong?
Solution
This is a called circular dependency. It is not an issue with Angular2 itself. It is not allowed in any language I am aware of.
You will need to refactor your code to remove this circular dependency. Likely you will need to breakup one of these services into new service.
If you follow the single responsibility principle you will find you won't get into circular dependency trap.
Answered By - Martin
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.