【问题标题】:Typescript Error TS2339: Property does not exist on type (Angular 12)打字稿错误 TS2339:类型上不存在属性(Angular 12)
【发布时间】:2021-10-02 21:28:03
【问题描述】:

我得到以下代码

错误 TS2339:“LogRepair[]”类型上不存在属性“时间戳”

在组件 html 中,我试图遍历在类型 LogRepair 中定义的任何属性数组:

<div>
<div *ngFor = "let repair of repairs" class="repair_list">
    <div class = "RT">{{repairs.name}}</div>
    <div class = "Repair Type">{{repairs.type}}</div>
    <div class = "Gecko Number">{{repairs.phoneID}}</div>
    <div class = "Warranty Sticker">{{repairs.stickerID}}</div>
    <div class = "Description">{{repairs.description}}</div>
    <div class = "Timestamp">{{repairs.timestamp}}</div>
</div>

在组件 ts 中,我正在导入 LogRepair 模型并声明一个名为 repairs 的属性:

import { Component, OnInit } from '@angular/core';
import { LogRepairService } from '../log-repair.service';
import { LogRepair } from '../LogRepair.model';


@Component({
  selector: 'app-view-repairs',
  templateUrl: './view-repairs.component.html',
  styleUrls: ['./view-repairs.component.scss']
})
export class ViewRepairsComponent implements OnInit {

  repairs: LogRepair[]=[];

  constructor(private logRepairService: LogRepairService){}
    // Called first time before the ngOnInit()
  ngOnInit(): void {
    // Called after the constructor and called after the first ngOnChanges() 

this.repairs = this.logRepairService.getRepairs();

  }
}

在服务 ts 中,我正在导出一个类 LogRepairService,它是 LogRepair 类型的硬编码数据数组。

import { Injectable } from '@angular/core';
import { LogRepair } from './LogRepair.model';

@Injectable({
  providedIn: 'root'
})
export class LogRepairService {

  repairs: LogRepair [] =[
  {name:"Tom",type:"standard",phoneID:"12345",stickerID:"ZX57B",description:"",timestamp: new Date ('2020-02-25T23:18:21.932Z') },
  {name:"Ben",type:"Warranty",phoneID:"54321",stickerID:"B76Gf",description:"touch ic",timestamp: new Date ('2021-02-25T23:18:21.932Z') },
  ];

  constructor() { }

  getRepairs(){
    return this.repairs;
  }

  postRepair(repairs:LogRepair){

  }
}

这是带有 timestamp 属性的模型 ts。

export interface LogRepair
{
   name: string;
   type: string;
   phoneID: string;
   stickerID: string;
   description: string;
   timestamp: Date;
}

由于接口导出中存在属性timestamp,我正在努力解决此错误。

【问题讨论】:

  • 更改所有这些:{{repairs.name}} 进行修复。 (单数,不是复数)..
  • 谢谢,成功了!

标签: angular typescript


【解决方案1】:

您正在尝试访问 LogRepair 数组上的属性,这就是错误消息在类型名称后包含方括号的原因。

我对 angular 不太熟悉,但我猜你是在说 repairs.timestamp 而你的意思是写 repair.timestamp 即循环中的当前元素而不是引用整个数组。

【讨论】:

  • 谢谢你,杰森!我将“repairs.X”更改为“repair.X”,效果很好。我对编码非常陌生,实际上并不知道应该引用循环表达式中声明的元素的名称。相反,我试图引用一些完全不同的东西!
猜你喜欢
  • 1970-01-01
  • 2021-10-22
  • 2016-12-12
  • 2016-08-11
  • 2018-03-15
  • 2020-12-18
  • 2018-08-02
  • 1970-01-01
  • 2017-03-26
相关资源
最近更新 更多