List current user's playlists and tracks on spotify - javascript

I'm trying to list all the playlists (and their tracks) of the current user on a Spotify integrated app using the API as explains in https://github.com/spotify/apps-tutorial/tree/1.0 .
Is there any way to do this? Or is not supported by now?
Using the 1.X API I did this:
var returnedLibrary;
require(['$api/library#Library'], function(Library) {
returnedLibrary = Library.forCurrentUser();
});
(From: https://developer.spotify.com/docs/apps/api/1.0/library_.html)
I suppose that my object returnedLibrary has all the playlists for the current user, isn't it? My problem is that I don't know what to do with this returned object and how to iterate through it.
Anyone knows how to access this information?
Thanks,

If you are interested in the user's playlists, you can do it like this:
var returnedLibrary;
require(['$api/library#Library'], function(Library) {
returnedLibrary = Library.forCurrentUser();
returnedLibrary.playlists.snapshot().done(function(snapshot) {
for (var i = 0, l = snapshot.length; i < l; i++) {
var playlist = snapshot.get(i);
// do something with playlist
}
});
});

Finally I have achieved my purpose:
var returnedLibrary;
require(['$api/library#Library'], function(Library) {
returnedLibrary = Library.forCurrentUser();
returnedLibrary.playlists.snapshot().done(function(snapshot) {
for (var i = 0, l = snapshot.length; i < l; i++) {
var playlist = snapshot.get(i);
aplay._collections();
aplay.tracks.snapshot().done(function(s){
selectedPlaylist = s;
for(k=0;k<s.length;k++){
s.get(k).name; //Will be the name of that song
}
});
}
});
});
Nevertheless, I don't know why I have to call aplay._collections(); (it seems is a private method). If I not do this call the tracks property is not set... Any ideas about this?
Thanks!

Related

JavaScript - push results from for loop into array (with SoundCloud API)

I have this function that iterates through a user's favourited track genres on SoundCloud, and then I want to push these results into an array however am having problems. Any suggestions?
SC.connect(function() {
SC.get('/me/favorites', function(favorites) {
console.log(favorites)
for (i = 0; i < favorites.length; i++) {
console.log(favorites[i].genre);
favorites[i].genre.push(meGenrePref);
}
var meGenrePref = [];
console.log(meGenrePref);
});
});
I'm not expert on SoundCloud APIs but watching your code I thought this solution:
var meGenrePref = [];
SC.connect(function(){
SC.get('/me/favorites',function(favorites) {
console.log(favorites);
for(var i = 0; i < favorites.length; i++)
{
console.log(favorites[i].genre);
meGenrePref.push(favorites[i].genre);
}
console.log(meGenrePref);
});
});
You were trying to push the contents to a wrong variable, which was the response from the API.
In this solution we are saving to meGenrePref all genres.

Clearing JS response

I am making a call to an API. The API returns a list of results. When it does so - the response is fed into an object which I then use to iterate through and display them.
Here is the function which does that:
var getAvailability = () => {
if (chosenData.hotel == "") {
showError("Please select a location before booking.");
$timeout(() => LTBNavService.setTab('location'), 50);
return;
}
searchResponse = {};
console.log(searchResponse);
WebAPI.getHotelAvailability(genSearchObject()).then((data) => {
searchResponse = data;
$timeout(() => $('[data-tab-content] .search-btn').first().focus(), 50);
generateRoomTypeObject(searchResponse);
}, (data) => searchResponse.error = data.data.errors[0].error);
};
The Problem:
The old results are still displayed until the new set of results are available. This causes a flicker and a delay which is a bad user experience.
The solution:(which i need help with)
What is the best possible way of handling this problem? Ideally, I would like to reset/clear the search response. As in, the new results are delivered and the old ones are cleared. Is this possible from within the getAvailability function?
What would be the best way to achieve this?
The Solution:
Thanks to #Daniel Beck for his suggestion to call the generateRoomTypeObject function and feed it an empty object - +1'd his comment.
This triggered an undefined error in my generateRoomTypeObject function where i was running a few length checks(makes sense, because the object was empty - so there was nothing to do length checks on).
I handled the error by handling the undefined exception and setting the searchResponse to an empty object.
var generateRoomTypeObject = (searchResponse) => {
var ratePlans = searchResponse.ratePlans,
errors = searchResponse.error,
roomTypes = [],
ignoreBiggerRooms = false;
rawRoomsObjs = [];
if (angular.isUndefined(errors)) {
// Iterate over the rate plan
if(ratePlans === undefined){
//generateRoomTypeObject -- Handle undefined by creating new object
searchResponse = {}
}else{
for (var i = 0; i < ratePlans.length; i++) {
var ratePlan = ratePlans[i],
rooms = ratePlan.rooms;
// Iterate over the rooms and add rooms to room object. Also keep a list of room types.
for (var j = 0; j < rooms.length; j++) {
//Stuff here
}
}
}
}

AngularJS - Is controller code executed line by line?

I'm new to AngularJS, and is experimenting AngularJS with Twitch API.
I have a list of channels that I'm interested in, defined as var channels.
Then I use the $http.get function to loop through another array, twitchList.channels, which contains the API addresses that I'm supposed to call.
(function() {
var app = angular.module('twitchList', []);
app.controller('twitchController', ['$http', function($http){
var twitchList = this;
twitchList.channels = [];
var channels = ["freecodecamp", "storbeck", "terakilobyte", "habathcx","RobotCaleb","thomasballinger","noobs2ninjas","beohoff", "MedryBW"];
for (var i = 0; i < channels.length; i++ ) {
twitchList.channels.push({
name: channels[i],
api: 'https://api.twitch.tv/kraken/streams/' + channels[i],
})
}
var data_list = [];
for (var j = 0; j < twitchList.channels.length; j++) {
$http.get(twitchList.channels[j].api).success(function(data){
data_list.push(data);
})
}
// Issue arises here!
console.log(data_list);
console.log(data_list.length);
}]);
})();
The API calls seems to be working perfectly, however, I need to get the results of the API call into an array, called data_list. Now, when I print data_list, and data_list.length, what happens is that data_list.length always returns 0, and data_list is sometimes populated (meaning it's either 0 size array or 9 size array). Even though the property of the array has a length 9, but calling .length always gives 0.
This let me think that the controller code is not executed line by line? Or is there something wrong with my logic?
Can someone give me a pointer? Thanks
No, this line:
data_list.push(data);
will be executed when you receive a response on the http request sent a line above. Hence the following lines:
console.log(data_list);
console.log(data_list.length);
will output [] and 0
I've not used it before, but could you possibly use $q.all in order to resolve multiple promises? I've used the equivalent $.when function in jQuery to achieve this in the past.
var data_list = [];
var promise_array = [];
var request;
for (var j = 0; j < twitchList.channels.length; j++) {
request = $http.get(twitchList.channels[j].api);
request.success(function(data) {
data_list.push(data);
});
promise_array.push(request);
}
$q.all(promise_array).then( function() {
console.log(data_list);
console.log(data_list.length);
});

Values won't to an array with a callback - JavaScript

I have this code:
rtclient.listFiles = function(callback) {
gapi.client.load('drive', 'v2', function() {
gapi.client.drive.files.list({
'maxResults': 20
}).execute(callback);
});
}
which I try to assign to an array using this code:
var arrayStore;
rtclient.listFiles(function(x) {
for(var i in x.items) {
arrayStore.push(x.items[i].id);
}})
However, the array arrayStore is not storing anything. This is using the Google Drive API and I am trying to access some file IDs to iterate over. Can anyone help?
the point is you should have a error like:
TypeError: Cannot call method 'push' of undefined
because you haven't defined it as an array, the other point is don't use for(...in) for arrays, you can find reasons about that in this post:
Why is using “for…in” with array iteration such a bad idea?
var arrayStore = [];
rtclient.listFiles(function(x) {
for(var i = 0; i < x.items.length; i++) {
arrayStore.push(x.items[i].id);
}
});
The other important point as #toothbrush has commented is, since the Google Drive API is asynchronous, you can't access the contents of arrayStore immediately, in other word to continue your scenario you should do something like this:
var arrayStore = [];
rtclient.listFiles(function(x) {
for(var i = 0; i < x.items.length; i++) {
arrayStore.push(x.items[i].id);
}
nextStep();
});
function nextStep(){
//here you would have access to arrayStore
console.log(arrayStore);
}

Lawnchair Phonegap Iteration Script

I am using Lawnchair for HTML5 iOS App Development for Persistant Storage.
I have an iteration script that returns undefined 11 times, here is the script
var lawnchair = Lawnchair({name:'relaxed', record:'config'}, function(people){
this.all(function(record, index) {
records = record.length;
couchURL = record.couchURL;
alert(records);
for(i = 0, len = records; i < len; i++){
console.log(couchURL);
}
})
})
The Data is obviously in local storage but isn't being iterated out correctly, could anybody provide a fix for this?
Thanks
Try this :
var lawnchair = Lawnchair({name:'relaxed', adapter:'dom'}, function(people){
})
this.all(function(data) {
for(var i = 0; i<data.length;i++)
{
Get data using this...data[i].value.fieldname
}
})

Categories

Resources