【问题标题】:*ngFor displaying data buy keep showing 'undefined' errors*ngFor 显示数据购买保持显示“未定义”错误
【发布时间】:2019-11-29 14:12:49
【问题描述】:

我是角度新手

我有一个 *ngFor 指令,它按预期运行并在我的浏览器中显示数据。虽然我的 chrome 控制台显示“未定义”错误。

类:

export class Matchlist {

    matches?: (MatchesEntity)[] | null;
    endIndex: number;
    startIndex: number;
    totalGames: number;




}



  export class MatchesEntity {
    lane: string;
    gameId: number;
    champion: number;
    platformId: string;
    timestamp: number;
    queue: number;
    role: string;
    season: number;
    Matchinfo : Match;
  }


  export class Match {
    seasonId: number;
    queueId: number;
    gameId: number;
    participantIdentities?: (ParticipantIdentitiesEntity)[] | null;
    gameVersion: string;
    platformId: string;
    gameMode: string;
    mapId: number;
    gameType: string;
    teams?: (TeamsEntity)[] | null;
    participants?: (ParticipantsEntity)[] | null;
    gameDuration: number;
    gameCreation: number;
  }
  export class ParticipantIdentitiesEntity {
    player: Player;
    participantId: number;
  }
  export class Player {
    currentPlatformId: string;
    summonerName: string;
    matchHistoryUri: string;
    platformId: string;
    currentAccountId: string;
    profileIcon: number;
    summonerId: string;
    accountId: string;
  }
  export class TeamsEntity {
    firstDragon: boolean;
    bans?: (BansEntity)[] | null;
    firstInhibitor: boolean;
    win: string;
    firstRiftHerald: boolean;
    firstBaron: boolean;
    baronKills: number;
    riftHeraldKills: number;
    firstBlood: boolean;
    teamId: number;
    firstTower: boolean;
    vilemawKills: number;
    inhibitorKills: number;
    towerKills: number;
    dominionVictoryScore: number;
    dragonKills: number;
  }
  export class BansEntity {
    pickTurn: number;
    championId: number;
  }
  export class ParticipantsEntity {
    spell1Id: number;
    participantId: number;

    spell2Id: number;
    teamId: number;
    stats: Stats;
    championId: number;
  }

  export class Stats {
    neutralMinionsKilledTeamJungle: number;
    visionScore: number;
    magicDamageDealtToChampions: number;
    largestMultiKill: number;
    totalTimeCrowdControlDealt: number;
    longestTimeSpentLiving: number;
    perk1Var1: number;
    perk1Var3: number;
    perk1Var2: number;
    tripleKills: number;
    perk5: number;
    perk4: number;
    playerScore9: number;
    playerScore8: number;
    kills: number;
    playerScore1: number;
    playerScore0: number;
    playerScore3: number;
    playerScore2: number;
    playerScore5: number;
    playerScore4: number;
    playerScore7: number;
    playerScore6: number;
    perk5Var1: number;
    perk5Var3: number;
    perk5Var2: number;
    totalScoreRank: number;
    neutralMinionsKilled: number;
    statPerk1: number;
    statPerk0: number;
    damageDealtToTurrets: number;
    physicalDamageDealtToChampions: number;
    damageDealtToObjectives: number;
    perk2Var2: number;
    perk2Var3: number;
    totalUnitsHealed: number;
    perk2Var1: number;
    perk4Var1: number;
    totalDamageTaken: number;
    perk4Var3: number;
    wardsKilled: number;
    largestCriticalStrike: number;
    largestKillingSpree: number;
    quadraKills: number;
    magicDamageDealt: number;
    firstBloodAssist: boolean;
    item2: number;
    item3: number;
    item0: number;
    item1: number;
    item6: number;
    item4: number;
    item5: number;
    perk1: number;
    perk0: number;
    perk3: number;
    perk2: number;
    perk3Var3: number;
    perk3Var2: number;
    perk3Var1: number;
    damageSelfMitigated: number;
    magicalDamageTaken: number;
    perk0Var2: number;
    firstInhibitorKill: boolean;
    trueDamageTaken: number;
    assists: number;
    perk4Var2: number;
    goldSpent: number;
    trueDamageDealt: number;
    participantId: number;
    physicalDamageDealt: number;
    sightWardsBoughtInGame: number;
    totalDamageDealtToChampions: number;
    physicalDamageTaken: number;
    totalPlayerScore: number;
    win: boolean;
    objectivePlayerScore: number;
    totalDamageDealt: number;
    neutralMinionsKilledEnemyJungle: number;
    deaths: number;
    wardsPlaced: number;
    perkPrimaryStyle: number;
    perkSubStyle: number;
    turretKills: number;
    firstBloodKill: boolean;
    trueDamageDealtToChampions: number;
    goldEarned: number;
    killingSprees: number;
    unrealKills: number;
    firstTowerAssist: boolean;
    firstTowerKill: boolean;
    champLevel: number;
    doubleKills: number;
    inhibitorKills: number;
    firstInhibitorAssist: boolean;
    perk0Var1: number;
    combatPlayerScore: number;
    perk0Var3: number;
    visionWardsBoughtInGame: number;
    pentaKills: number;
    totalHeal: number;
    totalMinionsKilled: number;
    timeCCingOthers: number;
    statPerk2: number;
  }


组件:

import { Component, OnInit, getDebugNode } from '@angular/core';
import { BaseService } from './../../services/base.service';
import { LeagueService } from './../../services/league.service';
import { MatchlistService } from './../../services/matchlist.service';
import { MatchService } from './../../services/match.service';
import { Account } from 'src/app/models/accounts';
import { League } from 'src/app/models/league';
import { Matchlist } from 'src/app/models/matchlist';
import { Match } from 'src/app/models/match';

@Component({
    selector: 'app-profil',
    templateUrl: './profil.component.html',
    styleUrls: ['./profil.component.css']
})
export class ProfilComponent implements OnInit {
    account = <Account>{};
    leagues = <League[]>[];
    Matchlists = <Matchlist>{};
    Match = <Match>{};
    timeLeft: number = 60;
    accountid: string;

    constructor(private baseService: BaseService, private leagueService: LeagueService
        , private matchlistService: MatchlistService, private matchService: MatchService) {
        LeagueService

    }

    ngOnInit() {
        this.baseService.Getinfo("capman").subscribe((data: Account) => {
            console.log(data);
            this.account = data;
            this.accountid = data.accountId;
            this.leagueService.Getleaugue(data.id).subscribe((leauguedata: League[]) => {
                this.leagues = leauguedata;
                this.leagues = this.leagues.filter(item => item.queueType !== "RANKED_TFT" && item.queueType !== "RANKED_FLEX_TT");
                this.leagues = this.leagues.sort((b, a) => a.queueType.localeCompare(b.queueType));
                //    console.log("account id " + JSON.stringify(this.leagues) );
            })
            this.matchlistService.Getmatchlist(this.accountid, 0, 5).subscribe((Matchlistdata: Matchlist) => {
                console.log(Matchlistdata);
                this.Matchlists = Matchlistdata;
                this.Matchlists.matches.forEach(va => {
                    this.matchService.GetMatch(va.gameId).subscribe((Matchinfodata: Match) => {
                        va.Matchinfo = Matchinfodata;
                        console.log(this.accountid);
                    })
                });
            })
        })
    }
}


html:

<div class="match1" *ngFor="let arg of Matchlists.matches" style="margin-top: 40px;" >
    <div *ngFor="let part of arg.Matchinfo.participantIdentities">

            <div *ngIf="part.player.accountId == accountid">



        {{Matchlist.Matchinfo.participants[part.participantId-1].spell1Id  | summonerSpell     }}
        {{Matchlist.Matchinfo.participants[part.participantId-1].spell2Id   | summonerSpell        }}       
        {{Matchlist.Matchinfo.gameId       }}   
        {{Matchlist.Matchinfo.participants[part.participantId-1].championId | championname }}

            </div>
            </div>
        </div>

错误: 错误类型错误:无法读取未定义的属性“participantIdentities”

在此处输入代码

提前致谢

【问题讨论】:

  • 我认为最好在问题中包含您的代码和错误,而不是发布屏幕截图。
  • 邮政编码而不是照片。并附上 html 代码,因为存在错误。您 ngFor 在数组被实例化之前对其进行迭代/当第一次迭代开始时某些变量尚未填充。
  • 发布代码而不是图片后:请正确格式化您的代码。
  • 问题的根源在于你不了解异步,以及发生的顺序。在 t0,Angular 实例化你的组件。在 t1,它调用 ngOnInit。在 t2,ngOnInit 发送 HTTP 请求以获取数据,并订阅以在数据可用时得到通知。在 t3,Angular 尝试渲染您的组件并失败,因为模板尝试显示尚未从服务器返回的数据。在 t98543665,响应最终从服务器返回,回调被调用并且数据可用于模板。使用 ngIf 仅显示可用的数据。
  • 您可以将两个 ngFor 包装在 ...-container> 快速解决。但是所有的ts逻辑都是一团糟。

标签: angular


【解决方案1】:

使用 ng-container 作为 ngFor 的包装来避免这种情况

<ng-container *ngIf="arg.Matchinfo">
  <div *ngFor="let part of arg.Matchinfo.participantIdentities">
   ...
  </div>
<ng-container>

【讨论】:

    【解决方案2】:

    您可以使用安全导航运算符?.

    <div class="match1" *ngFor="let arg of Matchlists.matches" style="margin-top: 40px;" >
      <div *ngFor="let part of arg.Matchinfo?.participantIdentities"> ?
          <div *ngIf="part.player.accountId == accountid">
          </div>
       </div>
    </div>
    

    safe navigation operator ( ? ) and null property paths

    【讨论】:

      猜你喜欢
      • 2019-05-06
      • 1970-01-01
      • 2021-06-17
      • 2018-06-05
      • 2021-04-28
      • 1970-01-01
      • 2023-03-20
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多