javascript - 为什么我收到错误 TypeError : "xyz" is not a function?

标签 javascript angular typescript

我有以下代码:

匹配组件

import { AllData } from './../../data-handling/all.data';
import { MatchService } from '../../data-handling/match.service';
import { Component, OnInit, Pipe, PipeTransform } from '@angular/core';
import { Match } from '../../data-handling/match';


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

  match: Match;

  constructor(private matchService: MatchService) { }

  ngOnInit() {
  }

  // ...
  loadMatch(): void {
    console.log(AllData.allMatches);
    this.match = AllData.allMatches[0];
    console.log(this.match);
  }

  getGame(match: Match): string {
    console.log('getGame');
    console.log(match); // prints the expected output (match object exists)
    match.getGameFromAll();
    return 'test';
  }
  // ...
}

匹配

export class Match {
    // ...

    public getGameFromAll(): void {
        console.log('XXXXXXXXXXX');
    }

    // ...
}

所有数据:

import { Match } from './match';

export class AllData {
    static allMatches: Match[];
}

和 html 模板:

<button (click)="loadMatch()">Load Match</button>
<!-- ... -->
<div *ngIf="match">
    <h4> {{getGame(match)}} </h4>
</div>
<!-- ... -->

我正在将所有带有 http 的匹配项加载到 allMatches 数组中。这样可行。之后我按下触发 Action 的按钮“加载匹配”,将单个匹配加载到 MatchComponent 中。从控制台输出来看也有效。

当匹配对象存在时,在MatchComponent中调用getGame函数。据我了解,运行代码后,网站上实际上应该出现文本“test”。但是在控制台中打印“getGame”后,它会显示以下内容:

ERROR TypeError: match.getGameFromAll is not a function

这很可能是一个简单的问题,但老实说,我并没有理解为什么我不能调用 getGameFromAll?

最佳答案

你的问题看起来很简单。您从 http 调用中获取的 json 对象不是原型(prototype)对象,因此没有在其中实现方法。

JSON 对象在变量名方面确实具有相同的成员,但它们没有构造函数、方法等。

如果您使用的是可观察对象,那么您将需要将 JSON 对象转换为 Prototype 对象,并在您订阅 http GET 请求的地方返回结果。

可以看看这个答案here

关于javascript - 为什么我收到错误 TypeError : "xyz" is not a function?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58664997/

相关文章:

javascript - Typescript 认为响应数组是一个对象

javascript - 1 秒后隐藏元素

javascript - Highcharts 具有多个区域范围和线系列的鼠标跟踪行为

javascript - Google map 信息窗口按钮 onclick

javascript - Mongoose 如何在exec回调函数中传递额外参数

angular - 在路由解析器中调度 ngrx 存储操作

javascript - 使用 RxJS 过滤单个值并返回一个可观察对象,并在 Angular 的模板中通过异步使用可观察对象

javascript - 为什么我应该使用 HttpClient 而不是 fetch?

angular - 如何在 ngFor 中使用响应式表单

angular - 如何在 ionic 中更改选项卡时弹出所有选项卡堆栈?