首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >为什么我得到错误的TypeError:"xyz“不是一个函数?

为什么我得到错误的TypeError:"xyz“不是一个函数?
EN

Stack Overflow用户
提问于 2019-11-02 03:40:32
回答 1查看 222关注 0票数 1

我有以下代码:

MatchComponent

代码语言:javascript
复制
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';
  }
  // ...
}

匹配

代码语言:javascript
复制
export class Match {
    // ...

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

    // ...
}

AllData:

代码语言:javascript
复制
import { Match } from './match';

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

和html模板:

代码语言:javascript
复制
<button (click)="loadMatch()">Load Match</button>
<!-- ... -->
<div *ngIf="match">
    <h4> {{getGame(match)}} </h4>
</div>
<!-- ... -->

我正在将所有与http匹配的内容加载到allMatches数组中。这是可行的。之后,我按下按钮“加载匹配”,该按钮触发了该操作,单个匹配被加载到MatchComponent中。从控制台的输出来看,这也是有效的。

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

代码语言:javascript
复制
ERROR TypeError: match.getGameFromAll is not a function

这很可能是一个简单的问题,但老实说,我不明白为什么我不能调用getGameFromAll?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2019-11-02 19:13:57

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

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

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

你可以看看这个答案here

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/58664997

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档