我正在尝试将控制器中的变量设置为函数的返回值。此函数在表中创建一个新条目,然后返回其ID。当我在chrome开发人员工具中进行调试时,可以看到我的功能正常运行response.data
,实际上是一个数字。但是,当我尝试为该函数调用设置变量时,该值被设置为undefined。
我的AngularJS组件:
function saveNewGame($http, gameData) {
var newGameData = {
"InvestigatorGroupUserId": gameData.GroupUserId,
"InvestigatorGroupGameId": gameData.GroupGameId,
"WithTeacher": gameData.WithTeacher
};
$http.post("/APGame.WebHost/play/newGamePlayed", newGameData)
.then(function(response) {
return response.data;
});
}
function controller($http) {
var model = this;
var gameData = model.value;
var gamePlayedId;
model.startGame = function() {
gamePlayedId = saveNewGame($http, gameData);
alert(gamePlayedId);
};
}
module.component("gameApp",
{
templateUrl: "/APGame/GameAngular/game-app.html",
controllerAs: "game",
bindings: {
value: "<"
},
controller: ["$http", controller]
});
这是我的服务电话正在执行的操作:
[OperationContract]
[WebInvoke(Method = "POST", RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json, UriTemplate = "newGamePlayed")]
int NewGamePlayed(GamePlayedData gamePlayedData);
public int NewGamePlayed(GamePlayedData gamePlayedData)
{
var gamePlayedRepo = _gamePlayedRepo ?? new GamePlayedRepository();
var newGame = new GamePlayed()
{
InvestigatorGroupUserId = gamePlayedData.InvestigatorGroupUserId,
InvestigatorGroupGameId = gamePlayedData.InvestigatorGroupGameId,
GameStartTime = DateTime.Now,
IsComplete = false
};
return gamePlayedRepo.Create(newGame);
}
原因是因为您的函数没有返回任何未定义的值。
$http.post("/APGame.WebHost/play/newGamePlayed", newGameData)
.then(function(response) {
// notice that you are returning this value to the function(response) not your saveNewGame function
return response.data;
});
由于javascript的异步性质,您应该改为执行类似操作。$ http.post返回一个promise对象,该对象可以如下使用。
return $http.post("/APGame.WebHost/play/newGamePlayed", newGameData);
并在您的调用函数中。
saveNewGame($http, gameData).then(function(response){
gamePlayedId = response.data;
});
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句