Tôi có thể làm điều này:góc 2: tiêm tài sản thay vì tiêm constructor
export class BaseComponent {
protected config: IConfig;
@Inject(AppConfig) protected appConfig: AppConfig;
constructor()
{
this.config = this.appConfig.getConfig();
}
thay vì điều này:
export class BaseComponent {
config: IConfig;
constructor(
private appConfig: AppConfig,
)
{
this.config = appConfig.getConfig();
}
Mục đích là để đơn giản hóa chữ ký constructor, vì vậy tất cả thành phần trẻ không cần phải chỉ định appConfig trong hàm tạo của chúng. Vì vậy, các thành phần được thừa kế từ BaseComponent trông như thế này:
@Component({
selector: 'sport-templates',
templateUrl: 'templates.component.html',
styleUrls: [ 'templates.component.scss' ],
encapsulation: ViewEncapsulation.None
})
export class SportTemplates extends BaseComponent implements OnInit {
constructor() {
super();
}
thay vì như thế này:
@Component({
selector: 'sport-templates',
templateUrl: 'templates.component.html',
styleUrls: [ 'templates.component.scss' ],
encapsulation: ViewEncapsulation.None
})
export class SportTemplates extends BaseComponent implements OnInit {
constructor(appConfig: AppConfig) {
super(appConfig);
}
Bạn đã phát hiện ra các giải pháp tốt nhất để tiêm constructor? – PaladiN
Tôi tìm thấy câu trả lời cho câu hỏi của mình tại đây: https://stackoverflow.com/questions/42461852/angular-2-inject-service-manually Cảm ơn. –