Tôi đã xem một ví dụ, và tôi đang buộc phải tái tạo nó. các name
và age
được khai báo bên trong class
và services
(Tiêm) được thêm vào trong constructor
.Tuyên bố biến khác nhau như thế nào giữa `lớp` và` hàm tạo`?
Tôi muốn biết sự khác nhau giữa việc khai báo biến với class
và constructor
tại đây. bất kỳ ai giúp tôi biết sự khác biệt.
Thay vì khai báo name
và age
, tôi có thể tự khai báo bên trong số construction
không?
đây là mã của tôi:
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);
}
}
Cảm ơn bài .. Tôi có một vấn đề. Các hàm lớp của tôi không thể tìm thấy cá thể dịch vụ của tôi được tiêm trong hàm tạo. Giải pháp là tôi phải thêm công cộng/riêng tư hoặc được bảo vệ trong khi tiêm vào constructor. Tôi đã tìm kiếm một lý do tại sao tôi cần phải làm như vậy và ở đây tôi đã nhận được câu trả lời của tôi. Cảm ơn @Angel – Jyotirmay
trong ví dụ của bạn _commonService ..... Không thể tìm thấy tên '_commonService'., Chỉ cần thêm riêng tư hoặc công khai bên trong hàm tạo() bạn giải quyết lỗi. hay không ? – stackdave