不要问题是什么。登录到控制台时会显示以下错误:
"Tipp: {
"id":1,
{...}
}
ERROR TypeError: this.tipp.isPersistent is not a function" is shown.
第一个日志语句正确显示。但是评估'this.tipp.isPersistent()'似乎是一个问题:
@Component({
selector: 'tipp-eingabe',
templateUrl: './tipp-eingabe.component.html',
styleUrls: ['./tipp-eingabe.component.css'],
encapsulation: ViewEncapsulation.None
})
export class TippEingabeComponent implements OnChanges {
@Input() tipp: Tipp;
constructor() {
}
ngOnChanges(changes) {
console.log("Tipp: " + JSON.stringify(this.tipp));
console.log("Tipp-isPersistent: " + this.tipp.isPersistent());
}
}
export class Tipp {
id: number;
spieler: Spieler;
spiel: Spiel;
tippErgebnis: Spielstand;
aenderungsDatum: Date;
public isPersistent(): boolean {
return true;
};
}
通过以下模板片段调用:
<div class="panel panel-default">
<div class="panel panel-body">
<div *ngFor="let spiel of spiele">
<div *ngIf="!isMatchCollapsed(spiel.id)">
<div *ngFor="let tipp of spiel.tipps" class="tippLine">
<tipp-eingabe [tipp]="tipp"></tipp-eingabe>
</div>
</div>
</div>
</div>
</div>
看起来您正在创建一个具有Tipp
属性的对象,而不是创建Tipp
的新实例。这意味着您的对象具有Tipp
的属性,但不具有方法。
因此,在将tipp传递给TippEingabeComponent的父组件中,您应该创建一个Tipp
的新实例。
let tipp = new Tipp(// pass in params);
这意味着您必须更新Tipp类才能接受参数
export class Tipp {
id: number;
spieler: Spieler;
spiel: Spiel;
tippErgebnis: Spielstand;
aenderungsDatum: Date;
constructor(obj: {
id: number;
spieler: Spieler;
spiel: Spiel;
tippErgebnis: Spielstand;
aenderungsDatum: Date;
}){
this.id = obj.id;
this.spieler = obj.spieler;
this.spiel = obj.spiel;
this.tippErgebnis = obj.tippErgebnis;
this.aenderungsDatu = obj.aenderungsDatum;
}
public isPersistent(): boolean {
return true;
};
}
现在,当你的TippEngabeComponent调用方法isPersistent时,它将存在于tipp上,因为tipp是类Tipp的一个实例。
你应该打电话给this.isPersistent()
console.log("Tipp-isPersistent: " + this.isPersistent());
ngOnChanges(changes) {
console.log("Tipp changed: " + JSON.stringify(this.tipp));
console.log("this.tipp instanceof Tipp: " + (this.tipp instanceof Tipp));
console.log("Tipp wurde geändert: " + this.tipp.isPersistent());
}
添加一些调试信息结果:
Tipp changed: {"id":1, ..... }
this.tipp instanceof Tipp: false
ERROR TypeError: this.tipp.isPersistent is not a function
由于日志输出表明tipp不是类Tipp的实例。但为什么不呢?数据作为来自后端服务的退出复杂json树的一部分提供。我认为树的嵌入叶子/节点的实例化是由角度处理的?
export class Spiel {
id: number;
:
tipps: Tipp[];
}
假设json中的数据服务提供的嵌入式“tipps”被实例化为“Spiel”类定义中声明的“Tipp”类型,这是错误的吗?
{
"id": 1,
"tipps": [
{
"id": 1,
"spieler": {
"id": 2,
"spielerName": "Stumbe",
"email": "[email protected]",
"rolle": "Spieler"
},
"tippErgebnis": {
"toreTeam1": 1,
"toreTeam2": 2
},
"aenderungsDatum": "2017-12-27T10:08:15"
},
{
"id": 2,
"spieler": {
"id": 3,
"spielerName": "Aug",
"email": "[email protected]",
"rolle": "Admin"
},
"tippErgebnis": {
"toreTeam1": 1,
"toreTeam2": 1
},
"aenderungsDatum": "2017-12-27T10:08:15"
}
]
}