2017-04-09 76 views
1

我有下面的類使用一個模型:無法在組件模板

export class Constants { 

public static cREQUESTED_SERVICE: string = "RequestedService"; 
} 

,我有以下模板組件(Service.component.html)(Service.component.ts):

<label>{{Constants.cREQUESTED_SERVICE}}</label> 

我已經導入(常量)類裏面(Service.component.html)。問題是:標籤顯示爲空,並記錄在控制檯以下錯誤:

Subscriber.js:240遺漏的類型錯誤:當以往任何時候都使用的是無法讀取的不確定

回答

3
在Service.component.ts

,像這樣創建

import { Constants } from 'your/path/to/this/file/Constants'; 

export class ServiceComponent { 
    get ConstantsClass() { 
    return Constants; 
    } 
} 

模板

<label>{{ConstantsClass.cREQUESTED_SERVICE}}</label> 
3

財產「cREQUESTED_SERVICE」常量你應該使用它們作爲注射劑(),因爲它們同樣通過留出的應用程序(單)的生命週期,就像任何其他供應商

@Injectable() 
export class Constants { 

public readonly cREQUESTED_SERVICE: string = "RequestedService"; 
} 

在你的組件,你應該注入的構造和使用

constructor(private cons : Constants){} 

this.cons.cREQUESTED_SERVICE 
+0

我不想類添加爲供應商 – Ala

+0

另一getter方法,但是這是做的方式。因爲你不應該有多個實例 – Aravind

+0

@Aravind你不能訪問類實例的靜態屬性 –