无法使用 Knockout.js 获取未定义或空引用 API 的 属性 'Id'

Unable to get property 'Id' of undefined or null reference API using Knockout.js

当我 运行 我的应用程序 "SCRIPT5007: Unable to get property 'Id' of undefined or null reference." 时出现以下错误 知道是什么导致此代码在文件处中断:app.js,行:51,列: 9?

下面是文件中的完整代码app.js.

var ViewModel = function () {
var self = this;
self.books = ko.observableArray();
self.error = ko.observable();
self.detail = ko.observable();
self.authors = ko.observableArray();
self.newBook = {
    Author: ko.observable(),
    Genre: ko.observable(),
    Price: ko.observable(),
    Title: ko.observable(),
    Year: ko.observable()
}

var booksUri = '/api/books/';
var authorsUri = '/api/authors/';

function ajaxHelper(uri, method, data) {
    self.error(''); // Clear error message
    return $.ajax({
        type: method,
        url: uri,
        dataType: 'json',
        contentType: 'application/json',
        data: data ? JSON.stringify(data) : null
    }).fail(function (jqXHR, textStatus, errorThrown) {
        self.error(errorThrown);
    });
}

function getAllBooks() {
    ajaxHelper(booksUri, 'GET').done(function (data) {
        self.books(data);
    });
}

self.getBookDetail = function (item) {
    ajaxHelper(booksUri + item.Id, 'GET').done(function (data) {
        self.detail(data);
    });
}

function getAuthors() {
    ajaxHelper(authorsUri, 'GET').done(function (data) {
        self.authors(data);
    });
}


self.addBook = function (formElement) {
    var book = {
        AuthorId: self.newBook.Author().Id,
        Genre: self.newBook.Genre(),
        Price: self.newBook.Price(),
        Title: self.newBook.Title(),
        Year: self.newBook.Year()
    };

    ajaxHelper(booksUri, 'POST', book).done(function (item) {
        self.books.push(item);
    });
}

// Fetch the initial data.
getAllBooks();
getAuthors();
};

ko.applyBindings(new ViewModel());

处理空作者案例非常简单。

self.addBook = function (formElement) {
    var author = self.newBook.Author() || {},
        book = {
            AuthorId: author.Id,
            Genre: self.newBook.Genre(),
            Price: self.newBook.Price(),
            Title: self.newBook.Title(),
            Year: self.newBook.Year()
        };
    //Is authorId required??
    if (!book.AuthorId) {
        throw new Error('Author ID required!');
    }

    ...
}