【问题标题】:How to map object from API to Angular input text如何将对象从 API 映射到 Angular 输入文本
【发布时间】:2022-01-05 18:40:18
【问题描述】:

我正在尝试读取 Angular 中的 API 响应并将其显示在输入文本字段中。我能够调用 API 并在控制台中打印响应,但我无法捕获对象中的响应并将其映射到输入字段。

记录 API 响应:

m-fin.services.ts

调用外部 API 的服务。

networth-home.component.ts

试图在变量中捕获响应。

networth-home.component.html

<div class = "account">
    <div class="field is-horizontal">
        <div class="field-label is-normal">
            <label class="label">Saving Account</label>
        </div>
        <div class="field-body">
            <div class="field">
                <div class="control">
                    <input class="input is-primary" type="text" placeholder= {{pages.account_amount}}>
                </div>
            </div>
        </div>
    </div>
</div>

错误:

Error: src/app/networth/networth-home/networth-home.component.html:27:86 - error TS2339: Property 'account_amount' does not exist on type 'string'.

27                     <input class="input is-primary" type="text" placeholder= {{pages.account_amount}}>
                                                                                        ~~~~~~~~~~~~~~

  src/app/networth/networth-home/networth-home.component.ts:6:16
    6   templateUrl: './networth-home.component.html',
                     ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    Error occurs in the template of component NetworthHomeComponent.

【问题讨论】:

    标签: angular spring-boot bulma


    【解决方案1】:

    您需要为从 API 获得的响应定义一个接口。目前 Typescript 将 pages 的类型推断为 string,因为您使用 '' 对其进行了初始化。

    如果对象中的键数是动态的但类型相同(数字),您可能可以执行以下操作:

    interface PagesItem {
     [key: string]: number;
    }
    
    pages: PagesItem[] = [];
    

    在您的 html 中:

    <input class="input is-primary" type="text" placeholder= {{pages[0]?.account_amount}}>
    

    【讨论】:

      猜你喜欢
      • 2018-04-14
      • 2021-09-03
      • 2022-01-01
      • 2023-03-17
      • 1970-01-01
      • 2019-10-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多