【问题标题】:Angular - Property does not exist on type 'Object'Angular - 类型“对象”上不存在属性
【发布时间】:2022-07-23 09:55:36
【问题描述】:

我在使用 Angular 时遇到了一些问题。

我正在尝试遍历 JSON API,但我收到了消息

“对象”类型上不存在属性。

不完全是,错误是

“项目”类型上不存在属性“冲刺”

我有这个 HTML 模板

<mat-toolbar>
    <span>{{ currentProject.title }}</span>
</mat-toolbar>
<div class="data-panel">
  <mat-card>
    <mat-toolbar style="border-radius: 4px 4px 0px 0px;">
              <span>Development</span>
          </mat-toolbar>
          <mat-card-content>
            <span>Access Code: {{ currentProject.accessCode }}</span>
            <div *ngFor="let sprint of currentProject.sprints">  <---- THIS IS WERE THE ERROR HAPPENS
              <span>{{ sprint }}</span>
            </div>
          </mat-card-content>
  </mat-card>
</div>

还有我的 JSON

{
    "id": 1,
    "title": "App Komputer",
    "description": "Website dedicated to computer related products",
    "accessCode": "5128",
    "createdAt": "2022-01-13T21:19:11.000Z",
    "updatedAt": "2022-01-13T21:19:16.000Z",
    "sprints": [{
        "id": 1,
        "title": "Sprint 1",
        "releaseDate": "2022-01-20T21:37:13.000Z",
        "description": "Specs up to 01/22/2022",
        "createdAt": "2022-01-13T21:37:58.000Z",
        "updatedAt": "2021-12-13T01:46:36.000Z",
        "projectId": 1,
        "specifications": [{
            "id": 1,
            "title": "Add product button",
            "description": "New product button HTML",
            "duration": 10,
            "status": 1,
            "createdAt": "2021-12-23T01:46:36.000Z",
            "updatedAt": "2021-12-23T01:46:36.000Z",
            "sprintId": 1
        }]
    }]
}

另外,这是我的组件

constructor(
    private projectService: ProjectService,
    private route: ActivatedRoute,
    private router: Router,
    private _titleService: Title
    ) { }

  ngOnInit(): void {
    if (!this.viewMode) {
      this.message = '';
      this.getProject(this.route.snapshot.params["id"]);
    }
  }

  getProject(id: string): void {
    this.projectService.get(id)
      .subscribe({
        next: (data) => {
          this.currentProject = data;
          console.log(data);
          this._titleService.setTitle(data.title+' · Scrumy');
        },
        error: (e) => console.error(e)
      });
  }

如何解决此错误?我尝试了很多方法,但都没有成功。

谢谢!


编辑 2022 年 1 月 22 日

对于那些询问的人,这里是 project-details-component.ts 的完整方案,我从中获取函数:

import { Component, Input, OnInit } from '@angular/core';
import { ProjectService } from 'src/app/services/project.service';
import { ActivatedRoute, Router } from '@angular/router';
import { Project } from 'src/app/models/project.model';
import { Title } from "@angular/platform-browser";
import { Moment } from 'moment';
import { EChartsOption } from 'echarts';

@Component({
  selector: 'app-project-details',
  templateUrl: './project-details.component.html',
  styleUrls: ['./project-details.component.css']
})
export class ProjectDetailsComponent implements OnInit {

  @Input() viewMode = false;

  @Input() currentProject: Project = {
    title: '',
    description: '',
    accessCode: ''
  };
  
  message = '';

  constructor(
    private projectService: ProjectService,
    private route: ActivatedRoute,
    private router: Router,
    private _titleService: Title
    ) { }

  ngOnInit(): void {
    if (!this.viewMode) {
      this.message = '';
      this.getProject(this.route.snapshot.params["id"]);
    }
  }

  getProject(id: string): void {
    this.projectService.get(id)
      .subscribe({
        next: (data) => {
          this.currentProject = data;
          console.log(data);
          this._titleService.setTitle(data.title+' · Scrumy');
        },
        error: (e) => console.error(e)
      });
  }

}

这是project.model.ts

export class Project {
  id?: any;
  title?: string;
  description?: string;
  accessCode?: string;
  createdAt?: Date;
  updatedAt?: Date;
}

【问题讨论】:

  • 请也分享项目服务
  • 也请分享Project 课程。我相信this.currentProjectProject 类型。
  • @TalhaAkca 我更新了帖子
  • @YongShun 我更新了帖子

标签: angular typescript object templates properties


【解决方案1】:

比较您的 JSON 数据和 Product 接口,您在模型中错过了 sprints 属性。

通过json2ts,你的Product接口应该如下:

export interface RootObject {
    id: number;
    title: string;
    description: string;
    accessCode: string;
    createdAt: Date;
    updatedAt: Date;
    sprints: Sprint[];
}

export interface Sprint {
    id: number;
    title: string;
    releaseDate: Date;
    description: string;
    createdAt: Date;
    updatedAt: Date;
    projectId: number;
    specifications: Specification[];
}

export interface Specification {
    id: number;
    title: string;
    description: string;
    duration: number;
    status: number;
    createdAt: Date;
    updatedAt: Date;
    sprintId: number;
}

另一个问题是@mat 提到的问题,因为currentProject 数据是异步的。您必须将值初始化为currentProject

@Input() currentProject: Project = {
  title: '',
  description: '',
  accessCode: '',
  sprints: []
};

或者当currentProjectnullundefined 时使用Typescript optional chaining (?.) 来转义错误。

@Input() currentProject: Project;
<mat-toolbar>
  <span>{{ currentProject?.title }}</span>
</mat-toolbar>
<div class="data-panel">
  <mat-card>
    <mat-toolbar style="border-radius: 4px 4px 0px 0px;">
      <span>Development</span>
    </mat-toolbar>
    <mat-card-content>
      <span>Access Code: {{ currentProject?.accessCode }}</span>
      <div *ngFor="let sprint of currentProject?.sprints">
        <span>{{ sprint | json }}</span>
      </div>
    </mat-card-content>
  </mat-card>
</div>

Sample Demo on StackBlitz

【讨论】:

    【解决方案2】:

    您不会也收到titleaccessCode 属性的错误吗?因为您将同步代码与异步代码混合在一起,这通常会导致您面临的问题。

    解释一下,您的模板期望 currentProject 立即可用,但事实并非如此,因为您是从某个服务加载它的。并且取决于您的模板需要多长时间才能从 currentProject 中提取数据,但它尚未初始化。

    如果您不想重写代码以使用 async 管道,请将整个块放入 *ngIf="!!currentProject", or add question marks before currentProject` 属性。

    <span>Access Code: {{ currentProject?.accessCode }}</span>
    <div *ngFor="let sprint of currentProject?.sprints">
      <span>{{ sprint }}</span>
    </div>
    

    【讨论】:

    • 嗨@mat.hudak!我没有从 currentProject.title 和 currentProject.accessCode 中得到任何错误。当我尝试遍历名为“sprints”的嵌套集合时,问题就开始了,它应该是用于 sprint 中的 sprint,但这不起作用:(
    猜你喜欢
    • 2021-04-02
    • 2018-11-04
    • 2020-10-31
    • 1970-01-01
    • 1970-01-01
    • 2019-05-18
    • 2017-12-02
    • 2020-08-27
    • 1970-01-01
    相关资源
    最近更新 更多