Q1。我有一个常见的实用程序类,其中包含一些实用程序/帮助程序方法(没有 get/post 请求)。我要问的第一件事是它应该是一个简单的类还是一个 @Injectable 类。因为在像这样导入任何组件类后都可以使用
import { Injectable } from '@angular/core';
Injectable()
export class Utils {
}
或者
export class Utils {
}
第二季度。如果它是可注入(inject)的,那么我必须将其导入到我的组件类中,注入(inject)到构造函数中,并且必须添加到提供者数组中,然后我可以使用注入(inject)类/服务的任何方法,例如
import { Utils } from './../shared/utils';
@Component({
moduleId: module.id,
selector: 'abc',
templateUrl: './abc.component.html',
providers: [Utils]
})
export class DemoComponent implements OnInit {
constructor(private _u: Utils) { }
ngOnInit(): void {
this._u.someMethod();
}
}
但除此之外,我可以直接访问服务方法,无需构造函数注入(inject),也无需添加提供程序,这是一种简短的方式,例如
import { Utils } from './../shared/utils';
@Component({
moduleId: module.id,
selector: 'abc',
templateUrl: './abc.component.html'
})
export class DemoComponent implements OnInit {
constructor() { }
ngOnInit(): void {
Utils.someMethod();
}
}
所以我想知道哪种方法更好并且值得推荐?
最佳答案
Q1。如果 Utils
不依赖于任何其他服务,则不需要 @Injectable()
,但如果它依赖于任何其他服务,则必须使用 @Injectable()
> 装饰器:
// 1 case
@Injectable() // <--- required
export class Utils {
constructor(private _otherService : OtherService){}
}
// 2 case
@Injectable() // <--- not required
export class Utils {
constructor(){}
}
在这两种情况下,您都必须将服务添加到组件的提供者数组中。
第二季度。使用第一种方法,因为它可以通过传递 MockUtils
服务轻松测试您的组件。
关于Angular 2 构造函数注入(inject)与直接访问,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42600444/