Jonathan Lightbringer
Jonathan Lightbringer

Reputation: 574

Assign array of JSON objects to array of interface Angular/Typescript

Currently, this works and doesn't give my error while running but my text editor is giving me an error that says property 'categories' does not exist on type 'CategoryInterface[]' (on the line where response.categories is assigned to variable) so I'm not sure if I'm doing things right.

    public categories: CategoryInterface[];

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

My backend returns this:

{
"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"
            }
        ]
    }
]

}

Upvotes: 1

Views: 2862

Answers (2)

Mehdi Benmoha
Mehdi Benmoha

Reputation: 3935

You are trying to cast your api response to an array of CategoryInterface which is not the case, you better use your subscribe method like this:

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

It's the your api response categories which needs to be casted to CategoryInterface[]

Bonus: The angular style-guide notice that you need to declare classes instead of interfaces and you don't have to suffix the class name with Interface, so just name your CategoryInterface to Category.

Upvotes: 1

twinklehawk
twinklehawk

Reputation: 639

You get the error because you declare response as a CategoryInterface[], but response.categories is actually the CategoryInterface[]. response is just a wrapper around the array. All the types are stripped out when the typescript is converted to javascript, which is why it works fine at runtime.

Upvotes: 0

Related Questions