如何使用 Fetch 和 Aurelia 打印发送表单数据的结果消息

How can I print a result message for sending form's data using Fetch and Aurelia

当我尝试在 Aurelia 中使用 fetch 获取 post 表单的数据并在成功时在同一网页上打印一条消息时,我收到错误 "Unhandled rejection TypeError: Cannot set property 'resultMessage' of undefined" (${resultMessage}) .

this.resultMessage = "New book added"; <= 此行导致错误

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": []
}

thisfunction 上下文中是函数,而不是 class。相反,使用箭头函数符号,如下所示:

.then(data => {
          if(data.id) {
             console.log(JSON.stringify(data));
             this.resultMessage = "New book added"; 
        })

现在 this 应该是 class.