【发布时间】:2017-06-13 17:36:00
【问题描述】:
我正在编写一个可能会呈指数级增长的服务,我希望能够编写单独的文件并将它们加载到组件使用的 @Injectable 中。通常我会编写多个服务并将每个服务注入到组件中,但是我的组件已经相当庞大,我觉得如果我可以加载一个服务并处理其中的所有功能,维护起来会更容易一项服务。我希望我只是没有搜索到正确的东西,这就像导入一样简单。
总体思路是这样的:
-configfns1.ts
-configfns2.ts(包含多个我希望作为config.service提供的ts函数)
-config.service.ts
import { Injectable } from '@angular/core'
//{{Possibly import functions here}}
@Injectable ()
export class ConfigService {
//{{Or possibly load within the class}}
}
-config-view.component.ts
import { Component, OnInit } from '@angular/core';
import { ConfigService } from '../services/config.service';
@Component({
selector: 'app-config-view',
templateUrl: './config-view.component.html',
styleUrls: ['./config-view.component.scss']
})
export class ConfigViewComponent implements OnInit {
constructor(private configService: ConfigService){ }
ngOnInit() {
this.configService.configfn1(); //<---This would be a function loaded from configfns1.ts, and injected from config.service.ts
})
onClick() {
this.configService.configfn2(); //Another fn loaded from configfns2.ts
}
}
这种方法可行吗?还是我只需要继续为每个服务创建单独的服务,然后将每个服务导入到我的组件中?
【问题讨论】:
标签: angular typescript angular2-services angular2-injection