Angular报错:类型ScoringRounds[]不存在name属性的问题咨询
问题分析
错误核心原因:scoringRoundsList是**ScoringRounds类型的数组**,数组本身没有name属性,只有数组内的单个ScoringRounds对象才具备name属性。你在服务方法中直接访问this.scoringRoundsList.name,相当于给数组本身调用name属性,自然触发类型错误。
解决步骤
1. 修正服务方法
修改scoring-rounds.service.ts中的方法,通过map提取每个回合的名称,同时修正返回类型:
// scoring-rounds.service.ts import { Injectable } from '@angular/core'; import { ScoringRounds } from './scoring.rounds'; @Injectable({ providedIn: 'root' }) export class ScoringRoundsService { protected scoringRoundsList: ScoringRounds[] = [ {id: 1, name: 'WA50', arrowsPerEnd: 6, numberOfEnds: 12, distanceOne: '50m', endsOne: 12, faceOne: '122cm', scoreType: 'Metric 10 Zone'}, {id: 2, name: 'WA1440', arrowsPerEnd: 6, numberOfEnds: 24, distanceOne: '90m', endsOne: 6, faceOne: '122cm', distanceTwo: '70m', endsTwo: 6, faceTwo: '122cm', distanceThree: '50m', endsThree: 6, faceThree: '80cm', distanceFour: '30m', endsFour: 6, faceFour: '80cm', scoreType: 'Metric 10 Zone'} ]; // 返回类型改为string[],对应名称数组 getAllScoringRoundNames(): string[] { // 遍历数组,提取每个回合的name属性 return this.scoringRoundsList.map(round => round.name); } // 可选:如果后续需要用到回合的其他属性,保留完整数据的方法 getAllScoringRounds(): ScoringRounds[] { return this.scoringRoundsList; } }
2. 组件中获取数据
在AddScoresComponent中注入服务,获取名称列表:
// add-scores.component.ts import { Component, OnInit } from '@angular/core'; import { ScoringRoundsService } from '../scoring-rounds.service'; @Component({ selector: 'app-add-scores', templateUrl: './add-scores.component.html', styleUrls: ['./add-scores.component.css'] }) export class AddScoresComponent implements OnInit { roundNames: string[] = []; constructor(private scoringRoundsService: ScoringRoundsService) {} ngOnInit(): void { this.roundNames = this.scoringRoundsService.getAllScoringRoundNames(); } }
3. 模板中绑定mat-select
在HTML模板中正确遍历名称数组:
<!-- add-scores.component.html --> <mat-form-field> <mat-label>选择计分回合</mat-label> <mat-select> <mat-option *ngFor="let name of roundNames" [value]="name"> {{ name }} </mat-option> </mat-select> </mat-form-field>
可选:绑定完整回合对象
如果后续需要使用回合的其他属性(如id、distanceOne等),可以直接返回完整数组并绑定:
组件中修改为:
rounds: ScoringRounds[] = []; ngOnInit(): void { this.rounds = this.scoringRoundsService.getAllScoringRounds(); }
模板中修改为:
<mat-form-field> <mat-label>选择计分回合</mat-label> <mat-select [(value)]="selectedRound"> <mat-option *ngFor="let round of rounds" [value]="round"> {{ round.name }} </mat-option> </mat-select> </mat-form-field>
错误提示解释
报错Property 'name' does not exist on type 'ScoringRounds[]'明确说明:你试图访问数组类型的name属性,但数组本身没有该属性,只有数组内的每个ScoringRounds对象才具备name属性。
内容的提问来源于stack exchange,提问作者Chris Docherty
相关产品推荐
相关产品推荐

