[英]Unable to get property 'Id' of undefined or null reference API using Knockout.js
运行应用程序“ SCRIPT5007:无法获取未定义或空引用的属性'Id'”时,出现以下错误。 关于什么导致此代码在File: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!');
}
...
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.