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
即使沒有可觀察到的東西,只是平坦的方法? –