鉴于以下JS,如何设置message
对象的PlateCheck
属性?
var plateCheck = {
plateNumber: '',
message: '',
alertClass: '',
checkPlate: function (plateNumber) {
PlateCheckService.checkPlate(plateNumber).then(function (response) {
var data = response.data;
if (data.VehicleAtl !== null) {
this.message = "Hot!";
this.alertClass = 'alert-danger';
} else {
this.message = "Plate #" + data.PlateNumber + " is clean.";
this.alertClass = 'alert-success';
}
});
}
};
修改
PlateCheckService.checkPlate(plateNumber)
返回承诺......
答案 0 :(得分:3)
这可能只是一个范围问题,但是通过调用plateCheck.checkPlate(fooPlateNumber)
来返回同一个对象可能会解决这个问题。
var plateCheck = {
plateNumber: '',
message: '',
alertClass: '',
checkPlate: function (plateNumber) {
var me = this;
PlateCheckService.checkPlate(plateNumber).then(function (response) {
var data = response.data;
me.plateNumber = plateNumber;
if (data.VehicleAtl !== null) {
me.message = "Hot!";
me.alertClass = 'alert-danger';
} else {
me.message = "Plate #" + data.PlateNumber + " is clean.";
me.alertClass = 'alert-success';
}
});
}
};
但也许您可以只提取服务功能,以便返回plateCheck
对象。
function checkPlate(plateNumber) {
var plateCheck = {};
plateCheck.plateNumber = plateNumber;
PlateCheckService.checkPlate(plateNumber).then(function (response) {
var data = response.data;
if (data.VehicleAtl !== null) {
plateCheck.message = "Hot!";
plateCheck.alertClass = 'alert-danger';
} else {
plateCheck.message = "Plate #" + data.PlateNumber + " is clean.";
plateCheck.alertClass = 'alert-success';
}
});
return plateCheck;
}