Reputation: 161
I've been struggling with handling retrieval of Spotify data in an Ionic service all day, and something that was working earlier now suddenly doesn't.
I have my login script set up in a service, and it is all working fine. However, after the console.log('updateInfo() called');
method inside updateInfo
, the program will skip the rest of the function, avoiding gathering the data from Spotify.
This is the entire service so far:
.factory('SpotifyService', function ($cordovaOauth, Spotify) {
var currentUser = {},
userId = '';
function login() {
console.log('login() called');
$cordovaOauth.spotify('583ac6ce144e4fcb9ae9c29bf9cad5ef', ['user-read-private', 'playlist-read-private']).then(function (result) {
window.localStorage.setItem('spotify-token', result.access_token);
Spotify.setAuthToken(result.access_token);
}, function (error) {
console.log("Error ->" + error);
});
}
function updateInfo() {
console.log('updateInfo() called');
Spotify.getCurrentUser().then(function (data) {
console.log('Gathering data');
currentUser = data;
userId = data.id;
console.log("CURRENT USER: " + userId + " - (" + currentUser + ")");
console.log('Done updating');
});
}
return {
getUser: function () {
console.log('SpotifyService.getUser() called');
var storedToken = window.localStorage.getItem('spotify-token');
if (storedToken !== null) {
console.log('Token accepted');
currentUser = updateInfo();
console.log('getUser function returns: ' + userId + " - (" + currentUser + ")");
//currentUser = Spotify.getCurrentUser();
} else {
console.log('getUser else accessed');
login();
}
return currentUser;
}
};
})
Any ideas as to why the Spotify.getCurrentUser()
method won't run?
Upvotes: 0
Views: 155
Reputation: 3752
It seems like your issue is with promises. If Spotify.getCurrentUser()
returns a promise you wouldn't know what the error is because you haven't defined a catch
statement. You should read Promises in Angular Explained as a Cartoon for a simple and clear explanation of promises.
Revise your code to add a catch statement:
Spotify.getCurrentUser()
.then(function (data) {
...
})
.catch(function(error){
console.log(error);
});
Upvotes: 3
Reputation: 487
Every time you use promises like $cordovaOauth.spotify() or Spotify.getCurrentUser() you have to define .catch block, that will help you debugging.
Add .catch block to the getCurrentUser() function call to track down your error and i would also recommend changing error callback pattern in auth function call into .catch block as well
.catch(function(error){
console.log(error);
});
Upvotes: 0