我有以下代码:
MatchComponent
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');
}
// ...
}AllData:
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数组中。这是可行的。之后,我按下按钮“加载匹配”,该按钮触发了该操作,单个匹配被加载到MatchComponent中。从控制台的输出来看,这也是有效的。
当存在match对象时,在MatchComponent中调用getGame函数。根据我的理解,在运行代码后,实际上应该在网站上出现文本"test“。但在控制台中打印"getGame“后,它会显示以下内容:
ERROR TypeError: match.getGameFromAll is not a function这很可能是一个简单的问题,但老实说,我不明白为什么我不能调用getGameFromAll?
发布于 2019-11-02 19:13:57
你的问题看起来很简单。您正在从http调用中获取json对象,这些对象不是原型对象,因此没有在其中实现方法。
JSON对象在变量名方面确实有相同的成员,但它们没有构造函数、方法等。
如果您使用的是observables,那么您将需要将JSON对象转换为Prototype对象,并在您订阅http GET请求的位置返回结果。
你可以看看这个答案here
https://stackoverflow.com/questions/58664997
复制相似问题