最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Set all the properties of a WebComponent element from a Json using an interface - Stack Overflow

programmeradmin1浏览0评论

I have a Card component and a Cards component. The Cards component groups a list of Card components that it obtains through an API. The problem is that I cannot fill all the properties of the Card component with the values ​​that I receive through the API in JSON format and using its corresponding iCard interface.

Card Interface:

export interface iCard {
    idx: number
    name: string
    value: string
    site: string
}

Card Component:

@customElement('sx-card')
export class AppCard extends LitElement implements iCard {
    @property({type: Number}) idx = 1;
    @property({type: String}) name = '';
    @property({type: String}) value = '';
    @property({type: String}) site = '';
    
    render() {
        return html`<span>${this.name}</span>`;
    }
}

Cards Component:

@customElement('sx-cards')
export class AppCards extends LitElement {
    connectedCallback(): void {
        super.connectedCallback();
        this.loadCards();
    }
    
    async loadCards(): void {
        let ajaxService = new AjaxService();
        let cards = await ajaxService.getCards();

        cards.forEach((card: iCard) => {
            let elCard: AppCard = document.createElement('sx-card') as AppCard;
            // This is where I need to pass the values ​​from the "card" response to the "elCard" component
            this.appendChild(elCard);
        });
    }
}

The Card component implements the iCard interface and the API response is an instance of the iCard interface, what I need is to pass the values ​​from the API response to the component. It seems to me that since the response is of type iCard and the component implements iCard there must be a better way than assigning them one by one.

And if you have any suggestions to improve the code I will appreciate it, I am learning TS.

发布评论

评论列表(0)

  1. 暂无评论