Angular 不能在组件模板中使用模型
我有以下课程:Angular 不能在组件模板中使用模型,angular,Angular,我有以下课程: export class Constants { public static cREQUESTED_SERVICE: string = "RequestedService"; } 我有组件(Service.component.ts)的以下模板(Service.component.html): {{Constants.cREQUESTED_SERVICE} 我已经在(Service.component.html)中导入了(常量)类。问题是:标签显示为空,控制台中记录了以下错误
export class Constants {
public static cREQUESTED_SERVICE: string = "RequestedService";
}
我有组件(Service.component.ts)的以下模板(Service.component.html):
{{Constants.cREQUESTED_SERVICE}
我已经在(Service.component.html)中导入了(常量)类。问题是:标签显示为空,控制台中记录了以下错误:
Subscriber.js:240 Uncaught TypeError:无法读取未定义的属性“cREQUESTED_SERVICE”当您使用常量时,您应该将它们作为可注入的()使用,因为它们在应用程序(singleton)的整个生命周期中保持不变,就像任何其他提供程序一样
@Injectable()
export class Constants {
public readonly cREQUESTED_SERVICE: string = "RequestedService";
}
在您的组件中,您应该注入构造函数并使用
constructor(private cons : Constants){}
this.cons.cREQUESTED_SERVICE
当您使用常量时,您应该将它们作为可注入()使用,因为它们在应用程序的整个生命周期(单例)中都保持不变,就像任何其他提供程序一样
@Injectable()
export class Constants {
public readonly cREQUESTED_SERVICE: string = "RequestedService";
}
在您的组件中,您应该注入构造函数并使用
constructor(private cons : Constants){}
this.cons.cREQUESTED_SERVICE
在Service.component.ts中,创建另一个getter方法,如下所示
import { Constants } from 'your/path/to/this/file/Constants';
export class ServiceComponent {
get ConstantsClass() {
return Constants;
}
}
模板中
<label>{{ConstantsClass.cREQUESTED_SERVICE}}</label>
{{ConstantsClass.cREQUESTED_SERVICE}
在Service.component.ts中,创建另一个getter方法,如下所示
import { Constants } from 'your/path/to/this/file/Constants';
export class ServiceComponent {
get ConstantsClass() {
return Constants;
}
}
模板中
<label>{{ConstantsClass.cREQUESTED_SERVICE}}</label>
{{ConstantsClass.cREQUESTED_SERVICE}
我不想将该类添加为Provider,但这是一种方法。因为你不应该有超过一个instance@Aravind无法从类访问静态属性instance@TiepPhan你说得对,我没注意到:)Updated@Aravind我将该类用作全局类,我不想在每个组件中为其添加引用。我不想将该类添加为Provider,但这就是方法。因为你不应该有超过一个instance@Aravind无法从类访问静态属性instance@TiepPhan你说得对,我没注意到:)Updated@Aravind我将该类用作全局类,不希望在每个组件中为其添加引用。