How do I initialize a TypeScript object with a JSON object

前端 未结 16 664
被撕碎了的回忆
被撕碎了的回忆 2020-11-22 08:30

I receive a JSON object from an AJAX call to a REST server. This object has property names that match my TypeScript class (this is a follow-on to this question).

Wha

16条回答
  •  南笙
    南笙 (楼主)
    2020-11-22 09:15

    **model.ts**
    export class Item {
        private key: JSON;
        constructor(jsonItem: any) {
            this.key = jsonItem;
        }
    }
    
    **service.ts**
    import { Item } from '../model/items';
    
    export class ItemService {
        items: Item;
        constructor() {
            this.items = new Item({
                'logo': 'Logo',
                'home': 'Home',
                'about': 'About',
                'contact': 'Contact',
            });
        }
        getItems(): Item {
            return this.items;
        }
    }
    

提交回复
热议问题