In my quest to create a simple web-based RPG game, I have set up a Java server that offers a REST API for a basic HTML5 application. This application features a service that displays quests organized by category and allows users to view detailed information about each quest retrieved through the REST API using the $resource dependency.
However, I encountered an issue with a specific service I defined as follows:
(function( ng, app ) {
"use strict";
// The quest repository service.
app.service(
"questService",
function( $q, $resource, $http, _, categoryService ) {
var QuestbookAPI = $resource( 'http://174.126.249.6\\:8080/worldcraft/quests' , {}, { query: {method: 'GET', isArray: true} });
var quests = [];
QuestbookAPI.query(function(newQuests){
console.log("I ran !!!!! WOOTZORS . I am the questbook api query.");
quests = newQuests;
_.each(quests, function(quest){
quest.id = quest.questID.id;
quest.categoryID = quest.questCategory.id;
});
});
// ***** general questbook api
function getQuestByID( id ){}
function getQuestsByCategory( categoryId ){}
....
// ***** end general questbook api
function getQuestsByCategoryID( categoryId ){}
// Return the public API.
return({
getQuestByID: getQuestByID,
getQuestsByCategoryId: getQuestsByCategoryId,
getRandomQuestExcluding: getRandomQuestExcluding,
});
}
);
})( angular, Worldcraft );
When the controller utilizing this service calls getQuestsByCategoryID, the resource query does not execute immediately. It only runs when I revisit the page, which populates the quests array as expected.
I am puzzled as to why the query isn't triggered right away. Could it be due to a fundamental concept that I am missing?
You can find the project's Git repository on GitHub at:
https://github.com/ClinkWorks/Worldcraft-UI
The live project can be accessed at:
To replicate the issue, navigate to quests, then combat, go back a level, and select combat again.
It seems like the getQuestsByCategoryID function is being called before QuestbookAPI.query() despite the fact the query is executed upon service declaration. I suspect it has something to do with promises or the $q object, but I'm unsure how to resolve it.