Last active
March 7, 2016 10:44
-
-
Save ispyinternet/9dc7395f958e160be84c to your computer and use it in GitHub Desktop.
DI Woes in angluar2
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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