【发布时间】:2018-03-18 04:48:07
【问题描述】:
第一季度。我有一个带有一些实用程序/帮助器方法的通用实用程序类(没有获取/发布请求)。我要问的第一件事是它应该是一个简单的类还是一个@Injectable 类。因为像这样在任何组件类中导入后两者都可以使用
import { Injectable } from '@angular/core';
Injectable()
export class Utils {
}
或
export class Utils {
}
第二季度。如果它是可注入的,那么我必须在我的组件类中导入它,在构造函数中注入,并且必须在提供者数组中添加,然后我可以使用注入的类/服务的任何方法,例如
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();
}
}
但除此之外,我可以直接访问服务方法而无需构造函数注入,也无需添加提供程序,这是一种类似于
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();
}
}
所以我想知道哪种方法更好且值得推荐?
【问题讨论】:
标签: angular service dependency-injection