我看过一个例子,我想要重现它.名称和年龄在类中声明,服务(Injectable)在构造函数中添加.
@H_404_10@我想知道在这里使用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); } }