当我尝试在Aurelia中使用fetch发布表单的数据并在同一网页上打印出一条消息(如果成功)时,我收到错误“Unhandled rejection TypeError:无法设置未定义的属性'resultMessage'($ {resultMessage}) 。
this.resultMessage =“新书增加”; <=此行导致错误
add.js:
import {HttpClient, json} from 'aurelia-fetch-client'
export class AddBooks{
bookData = {}
constructor() {
this.resultMessage = ""
}
activate() {
let client = new HttpClient();
}
addBook() {
let client = new HttpClient();
client.fetch('{address}', {
'method': "POST",
'body': json(this.bookData)
})
.then(function(response) {
return response.json();
})
.then(function(data) {
if(data.id) {
console.log(JSON.stringify(data));
this.resultMessage = "New book added";
}
});
}
}
add.html:
<template>
<form id="bookaddform" method="post" submit.delegate="addBook()">
<div>
<label for="bookTitle">Book Title</label>
<input id="bookTitle" type="text" name="bookTitle" value.bind="bookData.title">
</div>
<div>
<label for="bookPrice">Book Price</label>
<input id="bookPrice" type="number" name="bookPrice" value.bind="bookData.price">
</div>
<div>
<label for="bookDescription">Book Description</label>
<input id="bookDescription" type="text" name="bookDescription" value.bind="bookData.description">
</div>
<input type="submit" value="Add your book">
</form>
${resultMessage}
</template>
响应JSON
{
"id": "2",
"errors": []
}
this
语境中的function
是函数,而不是类。相反,使用箭头函数表示法,如下所示:
.then(data => {
if(data.id) {
console.log(JSON.stringify(data));
this.resultMessage = "New book added";
})
现在this
应该是班级。