我看过一个例子,我想要重现它.名称和年龄在类中声明,服务(Injectable)在构造函数中添加.
我想知道在这里使用class和constructor声明变量之间的区别.任何人都可以帮助我了解不同之处.
而不是声明名称和年龄不能我在建筑本身内声明?
这是我的代码:
import {Component} from 'angular2/core'; import {CommonService} from './commonService'; import {commonServiceIndipendent} from './commonSerivceIndipendent'; @Component({ selector : 'component1',template : ` <h1>Component 1</h1> <input type="text" #message /> <button (click)="onLog(message.value)" >Component1 - Message </button> `,providers:[commonServiceIndipendent] }) export class Component1 { name:string; //why here? age:number; //why here? //can't i add to constructor? if so how? constructor ( private _commonService : CommonService,private _commonServiceIndipendent:commonServiceIndipendent) {} //sending to same service. it has other instance in history onLog(message:string) { this._commonService.log( message ); this.name = "Arif",this.age = 20; this.onData(); } onData() { this._commonServiceIndipendent.myData(this.name,this.age); } }
在这种情况下
export class Component1 { constructor ( private _commonService : CommonService,private _commonServiceIndipendent:commonServiceIndipendent) { }
与此类似
export class Component1 { private _commonService : CommonService; private _commonServiceIndipendent:commonServiceIndipendent; constructor ( _commonService : CommonService,_commonServiceIndipendent:commonServiceIndipendent) { this._commonService = _commonService; this._commonServiceIndipendent = _commonServiceIndipendent; }
如果您不在构造函数protected,private或public中使用,例如DI,则变量_commonService的范围是您无法从另一个函数使用的构造函数{}的范围.
例如:
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'. }
如果您没有将它分配给具有该类范围的另一个变量,那么您不能使用此关键字引用此变量.
export class Component1 { name:string; //why here? age:number; //why here? //can't i add to constructor? if so how?
在没有Angular2的打字稿中,你可以做到这一点:
constructor (name:string,age:number) {}
但是在使用Angular2的打字稿中,Angular2负责在大多数情况下使用DI来实现:
constructor (private _commonServiceIndipendent:commonServiceIndipendent){}
你用于那些提供者:[commonServiceIndipendent].