我正在开发一个Dapp。我在前端使用Angular9。
我收到此错误:错误TypeError:无法读取未定义的属性“名称”。
我的代码是
app.component.ts
import { Component, OnInit } from '@angular/core';
import * as Donation from '../../Donation.json';
import { TypeDon } from './interfaces/TypeDon.js';
'use strict';
var Web3 = require('web3');
var DonationABI = Donation.abi;
const web3 = new Web3(new Web3.providers.HttpProvider('http://localhost:22000'));
const donationContract = new web3.eth.Contract(DonationABI, '0xd0a5685a4ba479D0FF4E86Ca8300738573816c63');
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
ngOnInit(): void {
this.getAllTypes();
}
title = 'donationApp';
typeDons : TypeDon[]=[];
getAllTypes(){
donationContract.handleRevert=true;
donationContract.methods.getAllTypeDon().call(function(error, result){
console.log("resultat :" + result);
if(!error){
if(result!=null) {
this.typeDons=result;
}
}
} else if(error)
{ console.log("error :" + error);}
});
}
}
app.component.html
<div style="text-align:center">
<h1>
Liste des donations :{{typeDons.length}}
</h1>
</div>
<table>
<thead>
<tr>
<th>Name</th>
<th>Description</th>
<th>Action</th>
</tr>
</thead>
<tbody>
<tr ngFor="let item of typeDons">
<td>{{ item.name }}</td>
<td>{{ item.description }}</td>
<td>
<button type="button" >Edit</button>
<button type="button" >Delete</button>
</td>
</tr>
</tbody>
</table>
app.module.ts
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { HttpClientModule } from '@angular/common/http';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
@NgModule({
declarations: [
AppComponent,
],
imports: [
FormsModule,
AppRoutingModule,
BrowserModule,
HttpClientModule,
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
我console.log记录表结果的内容,其中包含数据。
我认为该错误来自html。
任何解决问题的想法
答案 0 :(得分:3)
this
关键字定义的回调中,function
关键字的含义表示函数的范围。使用箭头函数来使用类成员变量。getAllTypes() {
donationContract.handleRevert = true;
donationContract.methods.getAllTypeDon().call((error, result) => { // <-- use arrow function here
console.log("resultat :" + result);
if(!error) {
if(result!=null) {
this.typeDons=result;
}
} else {
console.log("error :" + error);
}
});
}
?.
检查对象是否已定义。<tr ngFor="let item of typeDons">
<td>{{ item?.name }}</td> <!-- notice the question mark -->
<td>{{ item?.description }}</td>
<td>
<button type="button" >Edit</button>
<button type="button" >Delete</button>
</td>
</tr>
答案 1 :(得分:0)
在html中添加[1] "Respondent response text xxxxxxxx blahblahvlahblah blah blah blah and so on some more blah blah"
可以解决我的问题。