首页 > 解决方案 > 无法读取未定义的属性,但前端出现了东西

问题描述

我有两个问题,也许可以用相同的答案解决。我在前端的控制台中收到一个错误,它无法读取未定义的属性游戏。但是我的东西显示得很好。当我在前端/后端实现一个分页元素时,我也遇到了一个问题,它通过我的函数调用两次运行到后端并将所有内容都搞砸了。我假设这与订阅有关,但我不是 100% 确定。

我试过搞乱订阅,我在哪里调用 get games 函数,但我似乎无法让它不抛出错误。

This is my service: 
import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { environment } from '../../environments/environment';

interface Game {
  name: string;
}

@Injectable({
  providedIn: 'root'
})
  export class GameService {
    private url = environment.gamesAPI;

    httpOptions = {
      headers: new HttpHeaders({'Content-Type': 'application/json'})
    };

    constructor(private http: HttpClient) {}

    getAllGames(page) {
      console.log('11111111111111');
      const queryParams = `?page=${page}`;
      return this.http.get(this.url + queryParams);
    }
  }

这是我的 component.ts 文件

export class SportsCardsComponent implements OnInit, AfterViewInit {
  currentPage;
  chart: [];
  gamesArray;

  constructor(
    public games: GameService
  ) { }

  ngOnInit() {
    this.games.getAllGames(this.currentPage).subscribe(game => {
      this.gamesArray = game;
    });
  }

  ngAfterViewInit() {
    this.loadCharts();
  }

  onPageChange(pageData) {
    this.currentPage = pageData;
    this.games.getAllGames(this.currentPage).subscribe(game => {
      console.log(this.currentPage);
      this.gamesArray = game;
    });

    this.loadCharts();

  }

如您所见,我在 init 上调用 getAllGames() 函数,当发生这种情况时,我得到一个错误:ERROR TypeError: Cannot read property 'games' of undefined.

但是游戏在我的页面上显示得很好。任何想法为什么我会收到此错误?跟时间有关吗?

对于我的第二个问题,我的 onPageChange() 函数调用了相同的服务,我似乎无法让我的分页工作,由于某种原因,它似乎调用了两次 getAllGames() 函数。我假设这是因为我订阅了两次对数据库的调用?

HTML:

<div class="col-lg-9 float-right"
*ngIf="gamesArray"
>
  <!-- <div *ngIf='loading'  class="d-flex justify-content-center">
    <div class="spinner-border" style="width: 3rem; height: 3rem;" role="status"></div>
  </div> -->
  <!-- <div *ngIf="!loading"> -->
      <div class="row">
          <div class="col-lg-6 card-background"
            *ngFor="let game of gamesArray.games"
          >
            <div class="card-surround shadow-sm">
              <div>
                  <h2>{{game.homeTeam.teamName}}</h2>
                  <h2>{{game.awayTeam.teamName}}</h2>
                  <canvas id="{{game.id}}"></canvas>
                  <hr>
                  <p>{{game.gameTime}}</p>
              </div>
            </div>
        </div>
      </div>
  <!-- </div> -->
  <ngb-pagination
  class="d-flex justify-content-end"
  [collectionSize]="gamesArray.games.length"
  [(page)]="currentPage"
  [maxSize]="5"
  [pageSize]='6'
  (pageChange)='onPageChange($event)'
  size="sm"
  [rotate]="true"
  [ellipses]="false"
  [boundaryLinks]="true"
  ></ngb-pagination>
</div>

标签: node.jsangular

解决方案


在构造函数或声明中使用空数组初始化 gamesArray。渲染模板时,游戏服务仍在处理中。那时你的 gamesArray 属性是未定义的。


推荐阅读