我正在尝试将控制器中的变量设置为函数的返回值。此函数在表中创建一个新条目,然后返回其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);
}
答案 0 :(得分:2)
将promise promisement listener添加到方法调用中,如下所示:
model.startGame = function() {
gamePlayedId = saveNewGame($http, gameData)then(function(response) {
alert(response.data);
}, function(reason) {
alert('Failed: ' + reason);
});
};
返回http.get承诺而不是数据
function saveNewGame($http, gameData) {
var newGameData = {
"InvestigatorGroupUserId": gameData.GroupUserId,
"InvestigatorGroupGameId": gameData.GroupGameId,
"WithTeacher": gameData.WithTeacher
};
return $http.post("/APGame.WebHost/play/newGamePlayed", newGameData);
}
答案 1 :(得分:1)
原因是因为你的函数没有返回任何未定义的值。
$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;
});