I'm working on integrating Google OAuth in AngularJS. Below is the code snippet for creating a Google sign-in button and the corresponding callback function.
// Function for initializing Google sign-in
<script type="text/javascript>
a = function() {
var po = document.createElement('script'); po.type = 'text/javascript'; po.async = true;
po.src = 'https://apis.google.com/js/client:plusone.js';
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(po, s);
};
</script>
// Callback function after signing in
<script type="text/javascript>
var access_token = ''
function signinCallback(authResult) {
console.log(authResult)
if (authResult['status']['signed_in']) {
access_token = authResult['access_token']
if (window.location.pathname != "/album")
window.location = "/#/albums";
document.getElementById('signinButton').setAttribute('style', 'display: none');
} else {
console.log('Sign-in state: ' + authResult['error']);
}
}
</script>
The above code is triggered on every page load. It saves the access token provided by Google in a variable called access_token. I have an angular service that utilizes this access_token to interact with the Google API. Here is the code snippet for that -
picasaServices.factory('Phone', ['$resource',
function($resource){
return $resource('https://picasaweb.google.com/data/feed/api/user/default', {}, {
query: {method: 'GET', params:{alt: 'json', access_token: access_token}, isArray: false}
});
}
]);
The issue I'm facing is that the Angular service runs before Google returns the access token, causing it to execute with an empty access_token. How can I resolve this problem? I am also open to feedback on my overall approach.