angular - Does DI in Angular concern any external resource?
问题描述
I'm discovering Angular 7 and I was wondering how to use DI the best way.
My question is basically: should any object needed by a given component be injected?
I'm pretty sure the answer is no. I mean, services have certainly to be injected, because this is just a usual pattern.
But if for example a component needs a helper class, should this class be injected, like so:
import {CameraDimensionsHelper} from <file path>;
constructor (private cameraDimensions: CameraDimensionsHelper) {}
...or should it just be instanciated in a more "classical" way when needed, like so:
import {CameraDimensionsHelper} from <file path>;
private myMethod() {
const cameraDimensions = new CameraDimensionsHelper();
}
Thank you for you advice.
解决方案
这取决于助手类的用法。如果帮助器特定于单个组件,那么您可以创建该类的实例。如果帮助类为多个组件提供实用方法,则最好将其设为@Injectable()
并使用 DI。
推荐阅读
- r - ggmap mapdist() 在运行 devtools::install_github('dkahle/ggmap') 后不工作
- sql-server - 如何在 SQL Server 中创建复杂视图?
- json - ReactJS - 如何在使用 fetch 使用 json 文件时防止显示重复数据
- html - 在 Bootstrap 3 轮播错误上滑动
- ember.js - Ember:未捕获的错误:检测到无限渲染失效
- r - Stargazer 汇总表为空
- java - java蛇游戏(带圆圈)
- ocaml - OCaml 的 Hashtbl 的内存映射文件
- windows - 与 wab.exe 示例交互?
- google-apps-script - Google Apps 脚本 - 使用约会颜色创建日历事件