【问题标题】:How to inject class as new instance?如何将类作为新实例注入?
【发布时间】:2018-07-25 12:49:10
【问题描述】:

我有两个可注入类。

@Injectable()
export class Base {
value: string;
constructor() {
    this.value = "default value";
  }
}

@Injectable()
export class MyClass {
constructor(private base: Base) {
    base.value = "value from MyClass";
  }
}

我知道可注入类是单例的。所以MyClass 将覆盖Base 类中的value 用于所有应用程序(我将Base 类注入到MyClass 中)。但我只需要为MyClass 更改value。如何注入Base 而不是单例?如何注入Base 作为新实例?

【问题讨论】:

  • 这些类需要被注入服务吗?或者它们是否只是用于新建实例的简单类?
  • @DeborahK 是的,他们都应该被注入服务

标签: angular typescript dependency-injection


【解决方案1】:

你必须像这样在你的组件中提供“Base”和“MyClass”:

@Component({
...
providers: [
    Base,
    MyClass
   ]
})
export class ExampleComponent { 
   ...
}

【讨论】:

    猜你喜欢
    • 2017-02-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多