2017-03-04 65 views
1

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(); 
    } 
} 

顯示我想知道哪一個更好,推薦的方法一小段路?

回答

1

當你在構造函數中使用它,

  1. 您使用該服務的一個單獨的實例在您的組件。
  2. 當用作Injectable()時,應該在供應商模塊的數組內部聲明。

    constructor(private _u: Utils) { } 
         ngOnInit(): void { 
           this._u.someMethod(); 
         } 
    
    //private - _u => is specific inside this component 
    

在直接接入的情況下,資源被使用,因爲它是這可能會給下列問題

  1. 內存泄漏
  2. 少重用
  3. 在觀測的情況下,直到一個observable被取消訂閱,你不能再訂閱它。
+0

因此,每個幫助器類應該由構造器注入使用?如何在組件中單獨實現服務,因爲服務始終是單例? –

+0

不完全是,但在主要情況下是的,它應該被注射。 – Aravind

+0

即使沒有可觀察到的東西,只是平坦的方法? –

1

Q1。 @Injectable()如果Utils不依賴於任何其他服務是不需要的,但如果這樣做,你必須使用@Injectable()裝飾:

// 1 case 

    @Injectable() // <--- required 
    export class Utils { 
     constructor(private _otherService : OtherService){} 
    } 


    // 2 case 
    @Injectable() // <--- not required 
    export class Utils { 
     constructor(){} 
    } 

在您需要的組件的供應商陣列中添加的服務這兩種情況。 Q2302。使用第一種方法,因爲它可以通過傳遞MockUtils服務來輕鬆測試組件。