Все переменные, извлеченные из вложенного объекта, возвращают неопределенное - PullRequest
0 голосов
/ 01 апреля 2020

Я пытаюсь извлечь атрибут из вложенного объекта, и он работал раньше, но после повторного разрыва в систему установки / получения TypeScript он перестал работать.

Чтобы выяснить, где ошибка Происходит, я сделал console.log() отладку: D

stringify должен убедиться, что ключи определены при вызове кода:

console.log("selectedProtocol.info:")
console.log(JSON.stringify(this.selectedProtocol.info))
console.log("selectedProtocol.info.name:")
console.log(JSON.stringify(this.selectedProtocol.info.name))

В результате консоль выглядит как это:

"selectedProtocol.info:"                          main.js:1353:17
{"_Id":1,"_version":1,"_name":"test protocol"}    main.js:1354:17
"selectedProtocol.info.name:"                     main.js:1355:17
undefined

Итак, я попытался выяснить, была ли у меня ошибка в ссылках на атрибуты, поэтому я создал новый информационный объект и попробовал его:

var i = new Info(1, "test info", 1);
console.log("i:")
console.log(JSON.stringify(i))
console.log("i.name:")
console.log(JSON.stringify(i.name))

Это приводит к консоль выглядит следующим образом:

{"_Id":1,"_version":1,"_name":"test info"}       main.js:1359:17
"i.name:"                                        main.js:1360:17
"test info"

Здесь это сработало, поэтому я немного озадачен, почему он возвращает undefined? Я не знаю, какие классы могут быть релевантными, поэтому предоставили некоторые из них ниже:

export class Protocol {
    // vars
    private _Id: number;
    private _info: Info;
    private _supportedMethods: MethodWrapper[];
    private _connectionRequiredAttributes: AttributeWrapper[];
    private _canBeDiscovered: boolean;

    constructor(id: number, info: Info, supportedFunctions: MethodWrapper[], connectionRequiredAttributes: AttributeWrapper[] = undefined, canBeDiscovered: boolean = false) {
        this._Id=id;
        this._info = info;
        this._supportedMethods = supportedFunctions;
        this._connectionRequiredAttributes = connectionRequiredAttributes;
        this._canBeDiscovered = canBeDiscovered;
    }

    get Id() { return this._Id; }
    get supportedMethods() { return this._supportedMethods; }
    get info() { return this._info; }
    get canBeDiscovered() {return this._canBeDiscovered;}
    get connectionRequiredAttributes() {return this._connectionRequiredAttributes}
}

/**
 * sub class that stores general info
 */
export class Info {
    private _Id: number;
    private _name: string;
    private _version: number;

    constructor(ID: number, name: string, version: number) {
        this._Id = ID;
        this._version = version;
        this._name = name;
    }

    public get Id() { return this._Id }
    public get version() { return this._version }
    public get name() { return this._name }
}

Объект жестко запрограммирован прямо сейчас:

    export class ProtocolService {

  constructor() { }

  public testMethod() {
    console.log("method called")
  }

  private list = [
    new Protocol(
      1, // id
      new Info(1, "test p-protocol", 1), // info
      [
        new MethodWrapper(1, "method-1", this.testMethod, 
          [
            new AttributeWrapper(1, "owner1", undefined),
            new AttributeWrapper(2, "drift speed1", undefined)
          ])
      ],
      [
        new AttributeWrapper(1, "ip", undefined), 
        new AttributeWrapper(2, "username", undefined),
        new AttributeWrapper(2, "password", undefined)
      ]
    ),
    new Protocol(
      1,
      new Info(2, "test protocol", 2),
      [
        new MethodWrapper(1, "method-2", this.testMethod,
          [
            new AttributeWrapper(1, "owner2", undefined),
            new AttributeWrapper(2, "drift speed2", undefined)
          ])
      ],
      [
        new AttributeWrapper(1, "ip", undefined),
        new AttributeWrapper(2, "username", undefined),
        new AttributeWrapper(2, "password", undefined)
      ]
    )
  ]
...