【发布时间】:2016-03-22 06:52:48
【问题描述】:
我看到了一个例子,我正在尝试重现它。 name 和 age 在 class 和 services ( Injectable ) 中声明,在 constructor 中添加。
我想知道在这里用class 和constructor 声明变量之间的区别。任何人都可以帮助我了解差异。
除了声明 name 和 age 之外,我不能在 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);
}
}
【问题讨论】:
标签: typescript angular