Angular 2何时使用DI、提供程序或纯导入?
我有点困惑什么时候该用什么 1。使用静态函数定义类,只需导入并使用导入的名称和函数 共享类:Angular 2何时使用DI、提供程序或纯导入?,angular,typescript,dependency-injection,import,Angular,Typescript,Dependency Injection,Import,我有点困惑什么时候该用什么 1。使用静态函数定义类,只需导入并使用导入的名称和函数 共享类: export class SomeClass { static someFunction(){ ... } } export class SomeClassDI { public someFunctionDI(){ ... } } export class SomeClassBS { public someFunctionBS(){
export class SomeClass {
static someFunction(){
...
}
}
export class SomeClassDI {
public someFunctionDI(){
...
}
}
export class SomeClassBS {
public someFunctionBS(){
...
}
}
使用导出类的类:
import { SomeClass } from './someclassstatic'
...
constructor(){
SomeClass.someFunction()
}
import { SomeClassDI } from './someclassdi'
...
constructor(private theclassdi:SomeClassDI){
this.theclassdi.someFunction()
}
??? I am not sure what can be the example here.
2。定义标准类,然后通过DI安装
共享类:
export class SomeClass {
static someFunction(){
...
}
}
export class SomeClassDI {
public someFunctionDI(){
...
}
}
export class SomeClassBS {
public someFunctionBS(){
...
}
}
使用导出类的类:
import { SomeClass } from './someclassstatic'
...
constructor(){
SomeClass.someFunction()
}
import { SomeClassDI } from './someclassdi'
...
constructor(private theclassdi:SomeClassDI){
this.theclassdi.someFunction()
}
??? I am not sure what can be the example here.
3。定义标准类,然后在引导时装载为提供程序
共享类:
export class SomeClass {
static someFunction(){
...
}
}
export class SomeClassDI {
public someFunctionDI(){
...
}
}
export class SomeClassBS {
public someFunctionBS(){
...
}
}
类来引导Angular2
import { SomeClassBS } from './someclassbs'
...
bootstrap(AppComponent, [SomeClassBS]);
使用导出类的类:
import { SomeClass } from './someclassstatic'
...
constructor(){
SomeClass.someFunction()
}
import { SomeClassDI } from './someclassdi'
...
constructor(private theclassdi:SomeClassDI){
this.theclassdi.someFunction()
}
??? I am not sure what can be the example here.
如何正确使用提供者?这是一个有趣的问题。 首先,我建议你阅读这篇文章 但如果你想找一个简单的答案 1. 如果您想在代码中显示,您将得到一个错误,因为您不创建
类的实例,而只是尝试从构造函数调用函数。您可以重写这段代码,它会起作用,但如果您想遵循Angular2代码风格的最佳实践,这不是一个很好的解决方案
import { SomeClass } from './someclassstatic'
...
constructor(){
let someClass = new SomeClass();
someClass.someFunction()
}
仅作为工作代码的示例(您不应使用此代码)
2.
我相信Angular2会将错误返回给你。因为您不使用DI模式,所以只使用注入类,而从不注册它。你会得到这样的结果:
异常:SomeClass没有提供程序!(AppComponent->SomeClass)
因此,您可能不应该也使用这种编写代码的风格
3.
最后,最好的方法是在应用程序中使用DI模式。如果要在此组件中仅使用一次服务
,则可以将其包含到组件注释的提供者
属性中
@Component({
selector: 'my-app',
templateUrl: 'app/app.partial.html',
providers: [SomeClass]
})
export class AppComponent {
constructor(private someClass: SomeClass) {
this.someClass.someFunction();
}
}
如果您打算在多个不同的组件中使用服务
,您可以在应用程序的引导阶段将其注入中,而不必使用提供者将其注册到每个组件中,您只需将其注入构造函数中,如示例2所示,而且不会有错误
希望它能帮助你 @Teddy,它涵盖了你所有的问题吗?我得说角度2注射机制对我来说很奇怪。如果我必须导入注入类,这个DI有什么意义?DI不应该给我从IMLPemption中提取的可能性吗?我认为唯一真正的优势是DI允许您切换实际注入的内容。。。例如运行测试时。。。当ApiService被注入时。。它可以在运行时替换为ApiMockService。。诸如此类。或者,您也可以使用自己的密码切换系统错误文件夹。。无论什么地方,只要注射了ErrorHandler。。它会注射你的。