首页 > 解决方案 > 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.

标签: angulardependency-injection

解决方案


这取决于助手类的用法。如果帮助器特定于单个组件,那么您可以创建该类的实例。如果帮助类为多个组件提供实用方法,则最好将其设为@Injectable()并使用 DI。


推荐阅读