2017-10-21 40 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