gpt4 book ai didi

javascript - 将javascript变量设置为函数的返回值

转载 作者:行者123 更新时间:2023-11-29 19:11:32 26 4
gpt4 key购买 nike

我正在尝试将 Controller 中的变量设置为函数的返回值。此函数在表中创建一个新条目,然后返回其 ID。当我在 chrome 开发人员工具中进行调试时,我可以看到我的函数正常工作并且 response.data 实际上是一个数字。但是,当我尝试为此函数调用设置一个变量时,该值被设置为未定义。

我的 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);
}

最佳答案

向方法调用添加 promise 解析监听器,如下所示:

model.startGame = function() {
gamePlayedId = saveNewGame($http, gameData)then(function(response) {
alert(response.data);
}, function(reason) {
alert('Failed: ' + reason);
});
};

返回 http.get promise 而不是数据

function saveNewGame($http, gameData) {

var newGameData = {
"InvestigatorGroupUserId": gameData.GroupUserId,
"InvestigatorGroupGameId": gameData.GroupGameId,
"WithTeacher": gameData.WithTeacher
};

return $http.post("/APGame.WebHost/play/newGamePlayed", newGameData);
}

关于javascript - 将javascript变量设置为函数的返回值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38505666/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com