簡體   English   中英

將 JSON 對象數組分配給 Angular/Typescript 接口數組

[英]Assign array of JSON objects to array of interface Angular/Typescript

目前,這有效並且在運行時不會出現我的錯誤,但我的文本編輯器給了我一個錯誤,說類型“CategoryInterface[]”上不存在屬性“categories”(在 response.categories 分配給變量的那一行) ) 所以我不確定我是否做對了。

    public categories: CategoryInterface[];

          .subscribe((response: CategoryInterface[]) => {
          this.categories = response.categories;
          console.log(this.categories);
      });

我的后端返回這個:

{
"categories": [
    {
        "categoryId": 1,
        "name": "Important",
        "description": "This category is important.",
        "order": 1,
        "createdBy": null,
        "createdAt": "2017-11-25 12:09:04",
        "updatedBy": null,
        "updatedAt": "2018-01-17 23:53:25",
        "categoryBoards": [
            {
                "categoryBoardId": 1,
                "categoryId": 1,
                "name": "Announcements",
                "description": null,
                "order": 2,
                "createdBy": null,
                "createdAt": "2017-11-25 12:09:49",
                "updatedBy": null,
                "updatedAt": "2018-01-18 00:09:02"
            },
            {
                "categoryBoardId": 23,
                "categoryId": 1,
                "name": "Rules",
                "description": null,
                "order": 1,
                "createdBy": null,
                "createdAt": "2018-01-18 00:08:57",
                "updatedBy": null,
                "updatedAt": "2018-01-19 00:05:51"
            }
        ]
    }
]

}

您正在嘗試將您的 api 響應轉換為 CategoryInterface 數組,但情況並非如此,您最好像這樣使用您的訂閱方法:

.subscribe((response: any) => {
    this.categories = <CategoryInterface[]> response.categories;
    console.log(this.categories);
});

這是您需要轉換為 CategoryInterface[] 的 api 響應類別

獎勵:angular 樣式指南注意到您需要聲明類而不是接口,並且您不必在類名后綴 Interface,因此只需將 CategoryInterface 命名為 Category。

您收到錯誤是因為您將response聲明為CategoryInterface[] ,但response.categories實際上是CategoryInterface[] response只是數組的包裝器。 當打字稿轉換為 javascript 時,所有類型都會被去除,這就是它在運行時正常工作的原因。

暫無
暫無

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

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