2017-10-21 49 views
0

我有一個枚舉,我試圖注入一個角度的應用程序類。我怎樣才能讓我的課程認識到這個枚舉?

我不能讓打字稿承認枚舉的屬性,並得到錯誤Property 'xs' does not exist on type 'appBreakpoints'

代碼:

// appBreakpoints.ts file 
export enum appBreakpoints { 
    xs = 1, // convert xs to truthy value 
    sm, 
    md, 
    lg, 
    xl, 
    xxl 
} 

// In app.module 
import { appBreakpoints } from './appBreakpoints' 
@NgModule({ 
    providers: [ 
     { provide: appBreakpoints, useValue: appBreakpoints} 
    ] 
}); 

// In some service 
import { appBreakpoints } from './appBreakpoints'; 
import { Inject } from '@angular/core'; 
class MyClass { 
    constructor(@Inject(appBreakpoints) private appBreakpoints: appBreakpoints) { 
     if (0 < this.appBreakpoints.xs) { // TS ERROR: Property 'xs' does not exist on type 'appBreakpoints' 
      console.log('something being logged'); 
     } 
    } 
} 

我怎樣才能得到打字稿識別枚舉的屬性,所以我可以使用它們在我的班上?

回答

0

我不明白爲什麼要進行服務了此枚舉的insted的直接使用它從服務。

但問題是,所提供的值是枚舉appBreakpoints(即枚舉類本身),而爲型appBreakPoints的你在構造函數中注入什麼,因此被認爲是一個實例appBreakpoints的(即xs或sm等)。

爲了讓你的代碼工作,你需要改變服務到

constructor(@Inject(appBreakpoints) private bp: typeof appBreakpoints) { 
    if (0 < this.bp.xs) { 
     console.log('something being logged'); 
    } 
} 
+0

感謝。它讓我的代碼工作。我在app-config文件中有枚舉,只是想讓其他可能需要枚舉的服務可用。 – Jonathan002

0

爲什麼你想要使用角度DI呢?我猜它不夠的,只是導入該文件,並使用枚舉...

// In some service 
import { appBreakpoints } from './appBreakpoints'; 

class MyClass { 
    constructor() { 
     if (0 < appBreakpoints.xs) { 
      console.log('something being logged'); 
     } 
    } 
} 

總之,根據該角/ CLI問題,您應該使用InjectionToken得到這個工作:

你不能使用純粹的類型注入,例如一個枚舉或一個接口。 @jotatoledo指出,您將需要使用InjectionToken。請按照Angular的文檔獲取有關如何使用令牌的幫助。

https://github.com/angular/angular-cli/issues/8011

https://angular.io/api/core/InjectionToken