>我需要在 Typescript 中使用默认值创建一个类,因为我需要从我的所有应用程序访问此值,但我不想将值复制并粘贴到我需要使用它的每个组件中。
这是我的类代码:
export class WeightScale {
idIos: string
idAndroid: string
name: string
constructor(idIos: string = '123456ABC',
idAndroid: string = 'ABC:321:3567',
name: string = 'Device1')
{
this.idIos = idIos;
this.idAndroid = idAndroid;
this.name = name;
}
}
但是当我尝试访问类 ID 值时,出现此错误:
HomePage_Host.ngfactory.js?[sm]:1 错误类型错误:无法读取未定义的属性"idAndroid">
您应该编写一个服务,然后使用依赖关系注入通过构造函数将其注入。
在控制台中,您可以使用以下命令创建新服务:
ionic generate service services/WeightScaleService
然后将代码设置为如下所示:
import { Injectable } from '@angular/core';
@Injectable({
providedIn: 'root'
})
export class WeightScaleService {
constructor() { }
readonly idIos: string = '123456ABC';
readonly idAndroid: string = 'ABC:321:3567';
readonly name: string = 'Device1';
}
然后在这样的页面中使用它:
constructor(
public weightScaleService : WeightScaleService,
) {
}
something() {
let ios = this.weightScaleService.idIos;
}
更多理论可以在这里阅读:
- 何时在Ionic中使用提供商/服务/注射剂| joshmorony - 学习Ionic并使用Web Tech构建移动应用程序
然而
但是,我认为您的代码的实际问题是您只分配类型,而不是实例化它:
devices: WeightScale = new WeightScale();