Skip to content

Instantly share code, notes, and snippets.

@ispyinternet
Last active March 7, 2016 10:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ispyinternet/9dc7395f958e160be84c to your computer and use it in GitHub Desktop.
Save ispyinternet/9dc7395f958e160be84c to your computer and use it in GitHub Desktop.
DI Woes in angluar2
import sharedClass from 'sharedClass';
import childComponent from 'childComponent';
import serviceClass from 'serviceClass';
@Component({
selector: 'comp1',
providers: [sharedClass,childComponent,serviceClass],
template: '<h1>{title}</h1>'
})
class parentComponent {
constructor(private class1: sharedClass, private childComponent: childComponent, private service: serviceClass) {
}
}
//// sharedClass
@Injectable
class sharedClass {
constructor(confFromUser) {
this.callerId = confFromUser.id; // could only expose to class via custom factory class
this.instanceId = Math.random(); // reveals shared or new instances in console log
console.log(this.instanceId);
}
}
//// childComponent
@Component({
selector: 'comp1',
providers: [sharedClass,serviceClass],
template: '<h1>{title}</h1>'
})
class childComponent {
constructor(private class1: sharedClass, private service: serviceClass) {
// would instantiate new instances of sharedClass, serviceClass because of providers declaration
// but can't offer constructor config like { myCallerId: 'xx' }
}
}
//// childComponent2
@Component({
selector: 'comp1',
template: '<h1>{title}</h1>'
})
class childComponent {
constructor(private class1: sharedClass, private service: serviceClass) {
// gets shared parentComponent instances of sharedClass, serviceClass because of no providers declaration
}
}
// serviceClass
class serviceClass {
constructor(private class2: sharedClass) {
// class2 can only every be the same instance that was created for parentComponent - no ability to instantiate new
// because we cant offer a providers:[] declaration
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment