簡體   English   中英

具有字符串數組參數的Angular 5 / typescript類構造函數

[英]Angular 5 / typescript class constructor with string array argument

嘗試通過傳入字符串數組來構造類時,新的對象字符串數組為空。

我已經嘗試了幾種不同的方法來初始化構造函數中的新對象字符串數組,包括但不限於以下內容:

this.newArray = oldarray.slice();

this.newArray = Array.from(oldarray);

this.newArray = oldarray.map( s => { return s; });

迭代舊數組並將元素一次推入新數組。

這里有趣的是,在創建for循環時,我注意到字符串數組就像它有一個名為“array”的屬性。 所以for循環不會處理因為oldarray.length = 0 ,但是oldarray.array.length = 5

我能在調試器中看到這個。 如果我嘗試更改代碼以引用oldarray.array ,它會強調並抱怨.array部分並且無法在ng serve下編譯。

我知道這可能最終變得容易/愚蠢,而這只是我幾個小時盯着相同代碼的問題。

export class Widget {
  public role: string;
  public array: WidgetTuple[];

  constructor(role: string, tuplearray?: WidgetTuple[]) {
    this.role = role;
    this.array = [];
    if (tuplearray != undefined) {
      for (var lcv = 0; lcv < tuplearray.length; lcv++) {
        var tupl = new WidgetTuple(tuplearray[lcv].widgetGrouper);
        this.array.push(tupl);        
      }
    }
  }
}

export class WidgetTuple {
  public widgetGrouper: string[];

  constructor(strvalues?: string[]) {
    this.widgetGrouper = [];
    if (strvalues != undefined) {
      this.widgetGrouper = strvalues.slice();
      //this.widgetGrouper = strvalues.map()
      //for (var lcv = 0; lcv < strvalues.length; lcv++) {
      //  var entry = strvalues[lcv].toString();
      //  this.widgetGrouper.push(entry);
      //}
    }
  }
}

我希望原始widgetGrouper字符串數組中的字符串元素包含在添加到Widget數組的新WidgetTuple對象中。

到目前為止的所有嘗試,產生空字符串數組導致新創建的對象。

提前感謝您的協助。

這在我的評論中沒有很好地格式化,所以在這里,在VS中調試調試斷點並查看strvalues:

-       strvalues   Array(0) [] Object
+       array   Array(4) ["widgetone", "widgettwo", "someitem", …]  Object
        length  0   number
+       __proto__   Array(0) [, …]  Object

弄清楚了。 如果可以的話,我會刪除這個問題,但誰知道......這可能有一天會幫助其他人。

基本上,答案在於任何危險。

在組件視圖中,我為widget對象輸入了any類型。 在視圖中使用該對象時,該對象被錯誤地引用(添加數組屬性)。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM