【问题标题】:Property 'name' does not exist on type 'any[]' during ng build--aot在 ng build--aot 期间,类型“any []”上不存在属性“名称”
【发布时间】:2020-06-27 09:32:51
【问题描述】:

我有 1 个下拉菜单和 1 个输入字段。 根据下拉列表的选择,设置输入字段值。

所以我使用了 any(Array) 类型的数组。

在我的 .ts 文件中,我是这样写的

Services: Array<any>=[
    {name: 'Consultation', price: 100}, 
    {name: 'Follow Up', price: 200}, 
    {name: '24 Hrs. Creatinine', price: 300}, 
    {name: 'Complete Blood Count - CBC', price: 400}, 
    {name: 'X-Ray', price: 500}];

 selectedservice = this.Services;

而在 HTML 中,我写的是这样的

<div class="col-sm-9">
                <nb-select type="number" fullWidth id="service" [(ngModel)]="selectedservice"
                  [ngModelOptions]="{standalone: true}" required>
                  <nb-option *ngFor="let service of Services" [value]="service">{{service.name}} </nb-option>
                </nb-select>
</div>
<div class="col-sm-9">
                <input type="number" nbInput fullWidth id="price1" [disabled]="true"
                  value="{{selectedservice.price}}" class="form-control" />

当我运行构建命令时,ng build --aot

我遇到了这个错误

类型“any[]”上不存在属性“name”。

类型“any[]”上不存在属性“price”。

如何解决这个问题

【问题讨论】:

  • 您只提供了少量引用未知事物的代码。看起来有东西在调用 Services.nameServices.price,但你没有包括这些
  • selectedservice = this.Services;这个 varribale selectedservice 用于调用
  • 那是你的问题。

标签: angular ng-build


【解决方案1】:

当您想使用一个对象作为选定值时,您应该绑定到&lt;option&gt; 元素中的[ngValue]。当值为字符串时使用[value]

<div class="col-sm-9">
  <nb-select type="number" fullWidth id="service" 
      [(ngModel)]="selectedservice"
      [ngModelOptions]="{standalone: true}" required>
    <nb-option *ngFor="let service of Services" [ngValue]="service">
      {{service.name}} 
    </nb-option>
  </nb-select>
</div>

<div class="col-sm-9">
  <input *ngIf="selectedservice" type="number" nbInput fullWidth id="price1" [disabled]="true"
    value="{{selectedservice.price}}" class="form-control" />
</div>

用源数组初始化你的selectedservice也是没有意义的。您应该将其设置为您的选项之一。

selectedservice = this.Services[0];

演示:https://stackblitz.com/edit/angular-rg8myc

【讨论】:

    【解决方案2】:

    始终尝试提供有效的数据类型并避免使用任何类型。 最好创建一个接口并在您的代码中使用它。

    interface ServiceInterface {
      name: string;
      price: number;
    }
    

    在你的代码中使用这个接口。

    Services: ServiceInterface[] = [
            {name: 'Consultation', price: 100}, 
            {name: 'Follow Up', price: 200}, 
            {name: '24 Hrs. Creatinine', price: 300}, 
            {name: 'Complete Blood Count - CBC', price: 400}, 
            {name: 'X-Ray', price: 500}];
    

    当您在*ngFor 中使用它时,您想访问object 的属性,这意味着您假设它为object,但在声明中您已将其创建为任何数据类型的array。它无法从中找到任何类型信息并给您一个错误。

    【讨论】:

    • 这并不能回答问题?
    • 我需要创建ts文件来定义接口吗?
    • 你现在可以在同一个文件中创建这个接口,但是最好有一个单独的文件。
    猜你喜欢
    • 2021-02-08
    • 2018-09-11
    • 2019-12-10
    • 2019-09-20
    • 2018-09-09
    • 2019-12-31
    • 2021-11-29
    • 2022-12-17
    • 2020-11-20
    相关资源
    最近更新 更多