Directly from Parse.com javascript guide:
var GameScore = Parse.Object.extend("GameScore");
var query = new Parse.Query(GameScore);
query.get("xWMyZ4YEGZ", {
success: function(gameScore) {
// The object was retrieved successfully.
},
error: function(object, error) {
// The object was not retrieved successfully.
// error is a Parse.Error with an error code and message.
}
});
var score = gameScore.get("score");
var playerName = gameScore.get("playerName");
var cheatMode = gameScore.get("cheatMode");
Basically gives Uncaught ReferenceError: gameScore is not defined...
Here is my code to troubleshoot this:
// Retrieve class
var GameScore = Parse.Object.extend("GameScore"); //redefine the GameScore class based on the cloud.
var query = new Parse.Query(GameScore);
var my_object;
var some_object = query.get("SQV1DZXv5p", {
success: function(gameScore) { //gameScore is the retrieved object.
alert('Object retrieved, with object ID: ' + gameScore.id);
//document.getElementById('division1').innerHTML = gameScore.id;
my_object = gameScore.id;
},
error: function(object, error) {
alert('Retrieval FAILURE, error: ' + error.message + '; Object retrieved instead is: ' + object); //object will be NULL if not found.
}
});
var score = gameScore;
document.getElementById('division1').innerHTML = my_object;
So this still throws the reference error for gameScore.
Also, the document.getELementById statement does not print the gameScore.id in my division1 div. It remains empty. But when I check to see what my_object is in the javascript console, it returns the gameScore.id correctly.
What's interesting is if I run the document.getELementById line inside the success function, then it will display the gameScore.id...
Do this:
var GameScore = Parse.Object.extend("GameScore");
var query = new Parse.Query(GameScore);
query.get("xWMyZ4YEGZ", {
success: function(gameScore) {
// The object was retrieved successfully.
var score = gameScore.get("score");
var playerName = gameScore.get("playerName");
var cheatMode = gameScore.get("cheatMode");
},
error: function(object, error) {
// The object was not retrieved successfully.
// error is a Parse.Error with an error code and message.
}
});
gameScore is only be available in the scope of the success block, hence the Uncaught ReferenceError. The world outside the success block does not know it exists. Do your stuff in there.
Also, .get() makes a request from the server, so it would take time to complete. Performing operations gameScore after the .get() method will result in accessing that object when it has not been fetched yet, hence another error. See #danh's comment below. For network calls like this, always perform actions on the fetched object inside the completion block.
I'm using http interceptor. I do see all the values when I make a Restangular GET request. Here is the code for my request interceptor.
request: function (config) {
// see link below to see value of config
console.log('config', config);
// below returns full url except query string
console.log('location', $location.absUrl());
// $rootScope.cacheData is $cacheFactory
console.log('$rootScope', $rootScope.cacheData);
// only returns {id: "http", size: 3}
console.log('cache info', $rootScope.cacheData.info());
// below returns undefined
console.log('cache get', $rootScope.cacheData.get('http'));
// other codes removed since it's not related
// ........
// ........
// Return the config or wrap it in a promise if blank.
return config || $q.when(config);
},
config value : http://i.imgur.com/l0IsXbJ.png
Unfortunately, preparing the params captured manually is not 100% guaranteed that it will match what has been cached. I noticed that cacheFactory checks the exact string that was requested. So if our GET request's query parameters are age=12&name=scott then on our http interceptor, we prepare it the other way by putting name first then age(name=scott&age=12), cacheFactory won't find it.
So I'm trying to look for an angular service or factory that will return the full URL equal to the request we made. I tried $location but it's not giving the full GET request.
I just decided to parse the config and build it from scratch. It's working great :)
if ( config.method == 'GET' && (config.url.indexOf('v1/repeters') != -1) ) {
// Prepare the full path
var cachedUrlsLocalStorage;
var absolutePath = '';
_(config.params).keys().sort().each( function(key, index) {
var value = config.params[key];
absolutePath = absolutePath + key + '=' + value + (index < _(config.params).keys().value().length - 1 ? '&' : '');
});
cachedUrlsLocalStorage = JSON.parse(window.localStorage.getItem('cachedUrls'));
if (cachedUrlsLocalStorage) {
var exists = _.findIndex(cachedUrlsLocalStorage, function(cachedData) {
return cachedData.url == config.url + '?' + absolutePath;
});
if (!exists) {
cachedUrlsLocalStorage.push({url : config.url + '?' + absolutePath, timeExecuted : moment(), expiryTime : moment().add(10, 'minutes')});
window.localStorage.setItem('cachedUrls', JSON.stringify( cachedUrlsLocalStorage ));
}
} else {
cachedUrlsLocalStorage = [];
cachedUrlsLocalStorage.push({url : config.url + '?' + absolutePath, timeExecuted : moment(), expiryTime : moment().add(10, 'minutes')});
window.localStorage.setItem('cachedUrls', JSON.stringify( cachedUrlsLocalStorage ));
}
}
I am submitting an $http request to my server using this code below, yet all the of sudden Angular is complaining about an "Unexpected token , " somewhere.
function sendAggrRequestToServer(url) {
var deferred = $q.defer();
$http({
method: 'GET',
encoding: 'JSON',
headers: {
'Access-Control-Allow-Origin': 'true'
},
withCredentials: true,
url: url
}).success(function (data, status, headers, config) {
var retval = data;
deferred.resolve(retval);
}).error(function (data, status, headers, config) {
logErr("Error submitting aggregation request to server: " + status);
});
return deferred.promise;
}
The strange thing is that this exact URL works successfully both in the browser and in Fiddler. And the Json data is returned as expected. However, for some strange reason my javascript code is throwing this
exception:
[app] [HT Error] Unexpected token ,
Object {exception: SyntaxError, cause: undefined}
angular.js:9778
(anonymous function) angular.js:9778
logIt logger.js:55
logError logger.js:49
(anonymous function) logger.js:32
(anonymous function) config.exceptionHandler.js:26
deferred.promise.then.wrappedCallback angular.js:11322
(anonymous function) angular.js:11405
Scope.$eval angular.js:12412
Scope.$digest angular.js:12224
Scope.$apply angular.js:12516
done angular.js:8204
completeRequest angular.js:8412
xhr.onreadystatechange
And my URL is :
http://localhost:49479/api/aggr?sid=9630a8040ee6c901a4034c07894abc317272f855c757a4c60a6a&kri=[CDSStress%20A]:[USD%2010Y%20X%20-1.25],[CDSStress%20A]:[USD%2010Y%20X%201.25]&aggrFunc=SUM([CDSStress%20A]:[USD%2010Y%20X%20-1.25]),SUM([CDSStress%20A]:[USD%2010Y%20X%201.25])&dim=Counterparty
FYI: All appears to be fine in angular.js at this point in angular, and I can indeed see the response data (which is definitely valid Json data). The callback status param has a value of "200" and the statusText is 'OK':
function completeRequest(callback, status, response, headersString, statusText) {
// cancel timeout and subsequent timeout promise resolution
timeoutId && $browserDefer.cancel(timeoutId);
jsonpDone = xhr = null;
// fix status code when it is 0 (0 status is undocumented).
// Occurs when accessing file resources or on Android 4.1 stock browser
// while retrieving files from application cache.
if (status === 0) {
status = response ? 200 : urlResolve(url).protocol == 'file' ? 404 : 0;
}
// normalize IE bug (http://bugs.jquery.com/ticket/1450)
status = status === 1223 ? 204 : status;
statusText = statusText || '';
callback(status, response, headersString, statusText);
$browser.$$completeOutstandingRequest(noop);
}
};
Here is a screen image of the break point where I can inspect the "response" param:
However, as soon as it resolves the promise and returns to my calling function, angular throws the Unexpected token error.
I have been using this for days now, but today I must have introduced something to cause this. I just can't figure out what !
Your advice and guidance is greatly appreciated.
regards.
Bob
UPDATE:
I now find Angular throwing the actual exception inside $HttpProvider() on this line :
data = fromJson(data);
inside here :
function $HttpProvider() {
var JSON_START = /^\s*(\[|\{[^\{])/,
JSON_END = /[\}\]]\s*$/,
PROTECTION_PREFIX = /^\)\]\}',?\n/,
CONTENT_TYPE_APPLICATION_JSON = {'Content-Type': 'application/json;charset=utf-8'};
var defaults = this.defaults = {
// transform incoming response data
transformResponse: [function(data) {
if (isString(data)) {
// strip json vulnerability protection prefix
data = data.replace(PROTECTION_PREFIX, '');
if (JSON_START.test(data) && JSON_END.test(data))
data = fromJson(data);
}
return data;
}],
// transform outgoing request data
transformRequest: [function(d) {
return isObject(d) && !isFile(d) && !isBlob(d) ? toJson(d) : d;
}],
// default headers
headers: {
common: {
'Accept': 'application/json, text/plain, */*'
},
post: copy(CONTENT_TYPE_APPLICATION_JSON),
put: copy(CONTENT_TYPE_APPLICATION_JSON),
patch: copy(CONTENT_TYPE_APPLICATION_JSON)
},
xsrfCookieName: 'XSRF-TOKEN',
xsrfHeaderName: 'X-XSRF-TOKEN'
};
And sendAggregationREquest() is called from here :
function buildAndSendAggregationQuery() {
// iterate list in reportsContext , pass data to to sendAggregationRequest()
var userKRIs = vm.kriUserDataSource.get();
userKRIs.load();
var group;
var kri = '';
var aggrFunc = '';
var aggrKriFuncArray;
var dimension = vm.selectedDimen;
var dimenMulti = '';
var applyScenarioAggr = false;
if (vm.kriUserDataSource.data()[0].group == '99_HSVaR') {
applyScenarioAggr = true;
}
// Call function to build the aggr function. Return value is an array.
if (applyScenarioAggr) {
aggrKriFuncArray = reportsContext.buildAggrFunc(vm.kriUserDataSource.data(), 'AVERAGE');
}
else {
aggrKriFuncArray = reportsContext.buildAggrFunc(vm.kriUserDataSource.data(), 'SUM');
}
kri = aggrKriFuncArray[0];
aggrFunc = aggrKriFuncArray[1];
for (var i = 0; i < vm.multiSelectedDimen.length; i++) {
dimenMulti += vm.multiSelectedDimen[i] + ',';
}
dimenMulti = dimenMulti.substr(0, dimenMulti.length - 1); // ' remove final ","
sendAggregationRequest(kri, aggrFunc, dimension); //dimenMulti);
}
and finally, the response data that comes back from server prior to that exception:
{"status":"SUCCESS", "messages":[], "data":[{"attributes":[{"name":"Counterparty","type":"string"},{"name":"SUM(CDSStress A:USD 10Y X -1.25)","type":"double"},{"name":"SUM(CDSStress A:USD 10Y X 1.25)","type":"double"}],"rows":[{"id":0,"values":["Goldman",0.,0.]},{"id":1,"values":["IBM",0.,0.]},{"id":2,"values":["JP Chase",0.,0.]},{"id":3,"values":["MINESCONDIDA",0.,0.]},{"id":4,"values":["Merrill",0.,0.]},{"id":5,"values":["Nokia",0.,0.]},{"id":6,"values":["Pequot",0.,0.]},{"id":7,"values":["Pimco Fund A",0.,0.]},{"id":8,"values":["Pimco Fund B",0.,0.]},{"id":9,"values":["Deutsche",0.,0.]},{"id":10,"values":["Ditech",0.,0.]},{"id":11,"values":["GM Isuzu",0.,0.]},{"id":12,"values":["GM Opel",0.,0.]},{"id":13,"values":["GMAC",0.,0.]},{"id":14,"values":["GMAC Insurance",0.,0.]},{"id":15,"values":["GSAM",0.,0.]},{"id":16,"values":["General Insurance",0.,0.]},{"id":17,"values":["Genworth",0.,0.]},{"id":18,"values":["AIG",0.,0.]},{"id":19,"values":["Andor",0.,0.]},{"id":20,"values":["BARCLAYS",92.7731197209214,-10.1717767200607]},{"id":21,"values":["BHHSH",0.,0.]},{"id":22,"values":["BHPBFIN",0.,0.]},{"id":23,"values":["BHPSTEEUR",1468.80370935,-161.395632863801]},{"id":24,"values":["BHPSUS",0.,0.]},{"id":25,"values":["BLUESCOPEFIN",0.,0.]},{"id":26,"values":["CSFB",3.35029024626419,-0.367366071961442]},{"id":27,"values":["BLOSOFL",0.,0.]},{"id":28,"values":["GRMOBND",0.,0.]}]}]}
can you make a jsfiddle ? or at least show us how you call the sendAggrRequestToServer method.
It shouldbe
var promise = sendAggrRequestToServer(url);
promise.then(function(data) {
console.log('Success we got: ' + data);
}, function(reason) {
console.log('Failed we got: ' + reason);
}, function(update) {
console.log('Strange we got: ' + update);
});
Thx