我正在使用带有 typescript 的 asp.net MVC 5。在我的 View 模型中,我试图将 ajax 调用中接收的数据从我的 api 推送到我的 knockoutObservable 数组。即使我的数组已初始化(或者至少我认为应该如此)。
Errr : TypeError: Cannot read property 'push' of undefined
这是我的代码:
module Models {
export class ReservationDay {
date: KnockoutObservable<Date>;
place: KnockoutObservable<string>;
avaibleSlots: KnockoutObservable<number>;
instructorId: KnockoutObservable<string>;
constructor(date: Date, place: string, avaibleSlots: number, instructorId: string) {
this.date = ko.observable(date);
this.place = ko.observable(place);
this.avaibleSlots = ko.observable(avaibleSlots);
this.instructorId = ko.observable(instructorId);
}
}
}
module ViewModel {
import ReservationDay = Models.ReservationDay;
export class Calendar {
public days: KnockoutObservableArray<ReservationDay> = ko.observableArray<ReservationDay>();
constructor() {
this.getMonthCalendar(new Date());
}
getMonthCalendar(date: Date) {
var month = date.getMonth() + 1;
$.ajax({
url: 'myApiUrl' + month,
type: 'GET',
dataType: 'json',
async: false,
success(data, textStatus, xhr) {
if (data.length > 0) {
for (var i = 0; i < data.length; i++) {
console.log(this.days); // here is undefined
this.days.push(new ReservationDay(data[i].date,data[i].place,data[i].avaibleSlots, data[i].instructorId)); // in this line : error : TypeError: Cannot read property 'push' of undefined
}
console.log("ajax done.");
}
},
error(xhr, textStatus, errorThrown) {
console.log('Error in Operation');
}
});
}
这是我的观点:
@section Scripts{
@Scripts.Render("~/bundles/jquery")
@Scripts.Render("~/bundles/knockout")
@Scripts.Render("~/bundles/bootstrap")
@Scripts.Render("~/bundles/calendar")
<script type="text/javascript">
$(function () {
var vm = new ViewModel.Calendar(@Model);
ko.applyBindings(vm);
});
</script>
}
还有另一个问题,任何人都可以解释一下如何使用位于其他文件夹中而不是具有上述 View 模型的文件中的 ReservationDay.ts 类。 My folders img
提前谢谢您!
最佳答案
因为ajax
成功中的this
并不引用Calendar
的实例,而是引用ajax
设置对象。
您可以通过在 ajax 外部添加对 Calendar
实例的引用来解决此问题:
getMonthCalendar(date: Date) {
var self = this;
$.ajax({
........
........
success: (data, textStatus, xhr) => {
if (data.length > 0) {
for (var i = 0; i < data.length; i++) {
self.days.push((new ReservationDay(data[i].date,data[i].place,data[i].avaibleSlots, data[i].instructorId));
}
}
}
})
}
或者
您可以使用context
输入ajax设置
。这将设置所有 ajax
回调的自定义上下文。
$.ajax({
url: 'myApiUrl' + month,
type: 'GET',
context: this,
success: (data, textStatus, xhr) => {
console.log(this.days); // refers to the "Calendar" instance
}
....
});
<小时/>
要在结构中导入 ReservationDay
类,您可以执行以下操作:
import {ReservationDay} from "../viewmodel/calendar"
关于javascript - Typescript 无法推送到 knockout 可观察数组,因为即使在初始化后也未定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46863279/