Q1。我有一个公共实用程序类与一些实用程序/帮助器方法(没有获取/发布请求)。首先我要问的是,它应该是一个简单的课程还是一个@Injectable
课程。因为两者都可以进口任何组件类这样Angular 2构造函数注入vs直接访问
import { Injectable } from '@angular/core';
Injectable()
export class Utils {
}
OR
export class Utils {
}
Q2后使用。如果是注射的话,我不得不进口这在我的组件类,在构造函数注入,并且必须在供应商阵列添加,然后我就可以使用注射类/服务的任何方法像
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();
}
}
显示我想知道哪一个更好,推荐的方法一小段路?
因此,每个帮助器类应该由构造器注入使用?如何在组件中单独实现服务,因为服务始终是单例? –
不完全是,但在主要情况下是的,它应该被注射。 – Aravind
即使没有可观察到的东西,只是平坦的方法? –