Hello all, I am currently building a Single Page App based on Google Cloud Endpoints (REST Api) which uses Sammy.js for routing.
To be able to use Endpoints I need to load a Google javascript Library, by adding the following script tag at the end of the HTML page:
<script src="https://apis.google.com/js/client.js?onload=init"></script>
And In the "init" callback function, I have to load my Endpoint. Pls see https://cloud.google.com/appengine/docs/java/endpoints/consume_js for more details.
I have a Sammy route which displays a list of items coming from the Endpoint, through:
this.get('#/listAllItems', function () {
listItems(); // function which calls the Endpoint and displays the results
});
When I call this route from a button (or menu item) in the page, there is no problem, since the Google javascript Library is already loaded, as well as the Endpoint.
However, when I call this route directly via the browser's address
bar, I get a 500 Error because the javascript Library didn't have time
to load before the routing is triggered.
body 500 Error get /page.html#/listAllItems gapi.client is undefined
I found a solution by waiting the library (and the Endpoint) to be
loaded before calling the Endpoint with the code below. But I don't find
that very elegant and there are probably some better/more efficient
ways to handle this problem.
this.get('#/listAllItems', function () {
function checkGapi() {
if ((gapi.client) && (gapi.client.myEndpointApi)) {
listItems();
} else {
window.setTimeout(checkGapi, 50);
}
}
checkGapi();
});
Any suggestion would be very welcome, thanks in advance!
FYI, I've posted the same question on SO: http://stackoverflow.com/questions/32682147
var app = Sammy(...);
function
init() {
app.run();
}
function init() {
var ROOT = 'https://yourendpoint.appspot.com/_ah/api';
gapi.client.load(
'myEndpointApi',
'v1',
function() {
app.run();
},
ROOT);
}