Eitan K Eitan K - 4 months ago 14
AngularJS Question

Set javascript variable to return value of function

I am trying to set a variable in my controller to the return value of a function. This function is creating a new entry in a table, and then returning its id. When I debug in chrome developer tools, I can see that my function is working correctly and that

response.data
is in fact a number. However, when I try to set a variable to this function call, the value is being set as undefined.

My AngularJS component:

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]
});


This is what my service call is doing:

[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);
}

Answer

The reason is because your function is not returning any value thus undefined.

$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;
    });

Due to asynchronous nature of javascript, you should do something like instead. $http.post return a promise object which can be used like following.

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

And in your calling function.

saveNewGame($http, gameData).then(function(response){
    gamePlayedId = response.data;
});
Comments