I have seen an example, and I am trying to reproduce it. The name and age are declared inside the class and services ( In
in this case
export class Component1 {
constructor (
private _commonService : CommonService,
private _commonServiceIndipendent:commonServiceIndipendent) {
}
is similar to this
export class Component1 {
private _commonService : CommonService;
private _commonServiceIndipendent:commonServiceIndipendent;
constructor (
_commonService : CommonService,
_commonServiceIndipendent:commonServiceIndipendent) {
this._commonService = _commonService;
this._commonServiceIndipendent = _commonServiceIndipendent;
}
if you do not use in the constructor protected, private, or public, for example, DI, the range of the variable _commonService is the scope of the constructor { } you could not use from another function.
for example:
export class Component1 {
constructor (
_commonService : CommonService,
_commonServiceIndipendent:commonServiceIndipendent) {
_commonService .... Work
}
foo(){
_commonService ..... Cannot find name '_commonService'.
this._commonService ..... Property '_commonService' does not exist on type 'yourClass'.
}
If you not assign it to another variable that has the scope of the class,so you no could refer to this variable, with this keyword.
export class Component1 {
name:string; //why here?
age:number; //why here?
//can't i add to constructor? if so how?
in typescript without Angular2, you can do this with nothing more:
constructor (name:string, age:number) {}
but in typescript with Angular2, Angular2 is responsible, most of the time, to make use of DI for exaple here:
constructor (private _commonServiceIndipendent:commonServiceIndipendent){}
you use for that providers:[commonServiceIndipendent].
Angular2: Inject a non @Injectable class
How to use Dependency Injection (DI) correctly in Angular2?