创建 class 或具有默认值的接口以从打字稿中的任何地方访问

Create class or interface with default values to access from everywhere in typescript

我需要用默认值在 typescript 中创建一个 class,因为我需要从我的所有应用程序访问这些值,但我不想在我需要使用它的每个组件中复制和粘贴该值。

这是我的 class 代码:

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;
    }
     

}

但是当我尝试访问 class 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;
  }

可以在此处阅读更多理论:

但是

但是我认为您的代码的实际问题是您只是分配类型,而不是实例化它:

devices: WeightScale = new WeightScale();