Angular2 service to connect to the Spotify Web API
Based off eddiemoore's angular-spotify. Big thanks to him
Install angular2-spotify via npm. Use the --save property to save into your package.json file.
npm install angular2-spotify --save
Provide Spotify Service into your component (only provide in your root componenent, but remember to import the service to every class you want to use it)
import {Component} from '@angular2/core';
import {SpotifyService} from 'angular2-spotify/angular2-spotify';
@Component({
providers: [
SpotifyService,{
provide: "SpotifyConfig" ,
useValue: {
clientId: '<CLIENT_ID>',
redirectUri: '<CALLBACK_URI>',
scope: '<SCOPE>',
// If you already have an auth token
authToken: '<AUTH_TOKEN>'
}
}
]
})
export class AppComponent {...}
Most of the functions in Spotify do not require you to authenticate your application. However if you do need to gain access to playlists or a user's data then add the necessary scopes:
For example:
providers: [
SpotifyService,{
provide: "SpotifyConfig" ,
useValue: {
clientId: 'ABC123DEF456GHfddId789JKL',
redirectUri: 'http://www.example.com/callback.html',
scope: 'user-follow-modify user-follow-read playlist-read-private playlist-read-collaborative playlist-modify-public playlist-modify-private user-library-read user-library-modify user-read-private',
// If you already have an authToken
authToken: localStorage.getItem('angular2-spotify-token')
}
}
]
Inject Spotify into a component to gain access to all the functions available
constructor(private spotifyService: SpotifyService) {
}
Get Spotify catalog information for a single album.
this.spotifyService.getAlbum('AlbumID or Spotify Album URI');
Example:
this.spotifyService.getAlbum('0sNOF9WDwhWunNAHPD3Baj').subscirbe(data => {
console.log(data);
});
Get Spotify catalog information for multiple albums identified by their Spotify IDs.
this.spotifyService.getAlbums('Array or comma separated list of Album IDs');
Example:
this.spotifyService
.getAlbums('41MnTivkwTO3UUJ8DrqEJJ,6JWc4iAiJ9FjyK0B59ABb4,6UXCm6bOO4gFlDQZV5yL37')
.subscirbe(data => {
console.log(data);
});
Get Spotify catalog information about an album’s tracks. Optional parameters can be used to limit the number of tracks returned.
this.spotifyService.getAlbumTracks('AlbumID or Spotify Album URI', options);
Example:
this.spotifyService.getAlbumTracks('6akEvsycLGftJxYudPjmqK').subscirbe(data => {
console.log(data);
});
Get Spotify catalog information for a single artist identified by their unique Spotify ID or Spotify URI.
this.spotifyService.getArtist('Artist Id or Spotify Artist URI');
Example
this.spotifyService.getArtist('0LcJLqbBmaGUft1e9Mm8HV').subscirbe(data => {
console.log(data);
});
Get Spotify catalog information for several artists based on their Spotify IDs.
this.spotifyService.getArtists('Comma separated string or array of Artist Ids');
Example:
this.spotifyService
.getArtists('0oSGxfWSnnOXhD2fKuz2Gy,3dBVyJ7JuOMt4GE9607Qin')
.subscirbe(data => {
console.log(data);
});
Get Spotify catalog information about an artist’s albums. Optional parameters can be passed in to filter and sort the response.
this.spotifyService.getArtistAlbums('Artist Id or Spotify Artist URI', options);
Example: { album_type: 'album,single' }
Example:
this.spotifyService.getArtistAlbums('1vCWHaC5f2uS3yhpwWbIA6').subscirbe(data => {
console.log(data);
});
Get Spotify catalog information about an artist’s top tracks by country.
this.spotifyService.getArtistTopTracks('Artist Id or Spotify Artist URI', 'Country Code');
Example:
this.spotifyService
.getArtistTopTracks('1vCWHaC5f2uS3yhpwWbIA6', 'AU')
.subscirbe(data => {
console.log(data);
});
Get Spotify catalog information about artists similar to a given artist. Similarity is based on analysis of the Spotify community’s listening history.
this.spotifyService.getRelatedArtists('Artist Id or Spotify Artist URI');
Example:
this.spotifyService.getRelatedArtists('1vCWHaC5f2uS3yhpwWbIA6').subscirbe(data => {
console.log(data);
});
Discover new releases and featured playlists. User needs to be logged in to gain access to these features.
Get a list of Spotify featured playlists
this.spotifyService.getFeaturedPlaylists(options);
Example:
this.spotifyService
.getFeaturedPlaylists({ locale: "nl_NL", country: "NL" })
.subscirbe(data => {
console.log(data);
});
Get a list of new album releases featured in Spotify
this.spotifyService.getNewReleases(options);
Example:
this.spotifyService.getNewReleases({ country: "NL" }).subscirbe(data => {
console.log(data);
});
Get a list of categories used to tag items in Spotify (on, for example, the Spotify player’s “Browse” tab).
this.spotifyService.getCategories(options);
limit
to get the next set of categories.Example:
this.spotifyService.getCategories({ country: 'SG' }).subscirbe(data => {
console.log(data);
});
Get a single category used to tag items in Spotify (on, for example, the Spotify player’s “Browse” tab).
this.spotifyService.getCategory(category_id, options);
Example:
this.spotifyService.getCategory('party').subscirbe(data => {
console.log(data);
})
Get a list of Spotify playlists tagged with a particular category.
this.spotifyService.getCategoryPlaylists(category_id, options);
offset - number - Optional. The index of the first item to return. Default: 0 (the first object). Use with limit
to get the next set of items.
Example:
this.spotifyService.getCategoryPlaylists('party').subscirbe(data => {
console.log(data);
})
Create a playlist-style listening experience based on seed artists, tracks and genres.
this.spotifyService.getRecommendations(seed_*, options);
Adapt interface for Seed https://developer.spotify.com/web-api/get-recommendations/
offset - number - Optional. The index of the first item to return. Default: 0 (the first object). Use with limit
to get the next set of items.
Example:
this.spotifyService.getRecommendations( seed_tracks:'5h5tBFnbcVioFXiOixTn6', seed_artists:'0LcJLqbBmaGUft1e9Mm8HV' ).subscirbe(data => {
console.log(data);
})
Retrieve a list of available genres seed parameter values for recommendations
this.spotifyService.getAvailableGenreSeeds();
Example:
this.spotifyService.getAvailableGenreSeeds().subscirbe(data => {
console.log(data);
})
These endpoints allow you manage the list of artists and users that a logged in user follows. Following and unfollowing requires the user-follow-modify
scope. Check if Current User Follows requires the user-follow-read
scope.
Get the current user’s followed artists.
this.spotifyService.following('type', options)
artist
is supported.this.spotifyService.following('artist', { limit: 10 }).subscirbe(artists => {
console.log(artists);
})
Add the current user as a follower of one or more artists or other Spotify users.
this.spotifyService.follow('type', 'ids');
artist
or user
Example:
this.spotifyService.follow('user', 'exampleuser01').subscirbe(data => {
// no response from Spotify
});
Remove the current user as a follower of one or more artists or other Spotify users.
this.spotifyService.unfollow('type', 'ids');
artist
or user
Example:
this.spotifyService.unfollow('user', 'exampleuser01').subscirbe(data => {
// no response from Spotify
});
Check to see if the current user is following one or more artists or other Spotify users.
this.spotifyService.userFollowingContains('type', 'ids');
artist
or user
Example:
this.spotifyService.userFollowingContains('user', 'exampleuser01').subscirbe(data => {
console.log(data);
});
Add the current user as a follower of a playlist. Requires playlist-modify-public
or playlist-modify-private
scope to work.
this.spotifyService.followPlaylist('owner_id', 'playlist_id', isPublic);
Example:
this.spotifyService
.followPlaylist('jmperezperez', '2v3iNvBX8Ay1Gt2uXtUKUT', false)
.subscirbe(data => {
console.log(data);
});
Remove the current user as a follower of a playlist. Requires playlist-modify-public
or playlist-modify-private
scope to work.
this.spotifyService.unfollowPlaylist('owner_id', 'playlist_id', isPublic);
Example:
this.spotifyService
.unfollowPlaylist('jmperezperez', '2v3iNvBX8Ay1Gt2uXtUKUT')
.subscirbe(data => {
console.log(data);
});
Check to see if one or more Spotify users are following a specified playlist.Following a playlist can be done publicly or privately. Checking if a user publicly follows a playlist doesn't require any scopes; if the user is publicly following the playlist, this endpoint returns true.
Checking if the user is privately following a playlist is only possible for the current user when that user has granted access to the playlist-read-private
scope.
this.spotifyService
.playlistFollowingContains('owner_id', 'playlist_id', 'comma separated string or array of user ids');
Example:
this.spotifyService.playlistFollowingContains('jmperezperez', '2v3iNvBX8Ay1Gt2uXtUKUT', 'possan,elogain').subscirbe(data => {
console.log(data);
});
Get a list of the songs saved in the current Spotify user’s “Your Music” library. Requires the user-library-read
scope.
this.spotifyService.getSavedUserTracks(options);
this.spotifyService.getSavedUserTracks().subscirbe(data => {
console.log(data);
});
Check if one or more tracks is already saved in the current Spotify user’s “Your Music” library. Requires the user-library-read
scope.
this.spotifyService.userTracksContains('comma separated string or array of spotify track ids');
Example:
this.spotifyService
.userTracksContains('0udZHhCi7p1YzMlvI4fXoK,3SF5puV5eb6bgRSxBeMOk9')
.subscirbe(data => {
console.log(data);
});
Save one or more tracks to the current user’s “Your Music” library. Requires the user-library-modify
scope.
this.spotifyService.saveUserTracks('comma separated string or array of spotify track ids');
Example:
this.spotifyService
.saveUserTracks('0udZHhCi7p1YzMlvI4fXoK,3SF5puV5eb6bgRSxBeMOk9')
.subscirbe(data => {
console.log(data);
});
Remove one or more tracks from the current user’s “Your Music” library. Requires the user-library-modify
scope.
this.spotifyService.removeUserTracks('comma separated string or array of spotify track ids');
Example:
this.spotifyService
.removeUserTracks('0udZHhCi7p1YzMlvI4fXoK,3SF5puV5eb6bgRSxBeMOk9')
.subscirbe(data => {
console.log(data);
});
Get a list of the albums saved in the current Spotify user’s “Your Music” library. Requires the user-library-read
scope.
this.spotifyService.getSavedUserAlbums(options);
this.spotifyService.getSavedUserAlbums().subscirbe(data => {
console.log(data);
});
Save one or more albums to the current user’s “Your Music” library. Requires the user-library-modify
scope.
this.spotifyService.saveUserAlbums('comma separated string or array of spotify album ids');
Example:
this.spotifyService
.saveUserAlbums('4iV5W9uYEdYUVa79Axb7Rh,1301WleyT98MSxVHPZCA6M')
.subscirbe(data => {
console.log(data);
});
Remove one or more albums from the current user’s “Your Music” library. Requires the user-library-modify
scope.
this.spotifyService.removeUserAlbums('comma separated string or array of spotify album ids');
Example:
this.spotifyService
.removeUserAlbums('4iV5W9uYEdYUVa79Axb7Rh,1301WleyT98MSxVHPZCA6M')
.subscirbe(data => {
console.log(data);
});
Check if one or more albums is already saved in the current Spotify user’s “Your Music” library. Requires the user-library-read
scope.
this.spotifyService.userAlbumsContains('comma separated string or array of spotify album ids');
Example:
this.spotifyService
.userAlbumsContains('4iV5W9uYEdYUVa79Axb7Rh,1301WleyT98MSxVHPZCA6M')
.subscirbe(data => {
console.log(data);
});
Get the current user’s top artists based on calculated affinity. Requires the user-top-read
scope.
this.spotifyService.getUserTopArtists(options);
limit
to get the next set of items.time_range - string - Optional. Over what time frame the affinities are computed. Valid values: long_term (calculated from several years of data and including all new data as it becomes available), medium_term (approximately last 6 months), short_term (approximately last 4 weeks). Default: medium_term.
Example:
this.spotifyService.getUserTopArtists().subscirbe(data => {
console.log(data);
})
Get the current user’s top tracks based on calculated affinity. Requires the user-top-read
scope.
this.spotifyService.getUserTopTracks(options);
limit
to get the next set of items.time_range - string - Optional. Over what time frame the affinities are computed. Valid values: long_term (calculated from several years of data and including all new data as it becomes available), medium_term (approximately last 6 months), short_term (approximately last 4 weeks). Default: medium_term.
Example:
this.spotifyService.getUserTopTracks().subscirbe(data => {
console.log(data);
})
User needs to be logged in to gain access to playlists
Get a list of the playlists owned by a Spotify user. Requires the playlist-read-private
scope
this.spotifyService.getUserPlaylists('user_id', options);
Example:
this.spotifyService.getUserPlaylists('wizzler').subscirbe(data => {
console.log(data);
});
Get a list of the playlists owned or followed by the current Spotify user. Requires the playlist-read-private
scope
this.spotifyService.getCurrentUserPlaylists(options);
Example:
this.spotifyService.getCurrentUserPlaylists().subscirbe(data => {
console.log(data);
});
Get a playlist owned by a Spotify user.
this.spotifyService.getPlaylist('user_id', 'playlist_id', options);
this.spotifyService
.getPlaylist('1176458919', '6Df19VKaShrdWrAnHinwVO')
.subscirbe(data => {
console.log(data);
});
Get full details of the tracks of a playlist owned by a Spotify user. Requires the playlist-read-private
scope.
this.spotifyService.getPlaylistTracks('user_id', 'playlist_id', options);
Example:
this.spotifyService
.getPlaylistTracks('1176458919', '6Df19VKaShrdWrAnHinwVO')
.subscirbe(data => {
console.log(data);
});
Create a playlist for a Spotify user. (The playlist will be empty until you add tracks.) Creating a public playlist requires the playlist-modify-public
scope. Creating a private playlist requires the playlist-modify-private
scope.
this.spotifyService.createPlaylist('user_id', options);
Example:
this.spotifyService
.createPlaylist('1176458919', { name: 'Awesome Mix Vol. 1' })
.subscirbe(data => {
console.log('playlist created');
});
Add one or more tracks to a user’s playlist. Adding tracks to a public playlist requires the playlist-modify-public
scope. Adding tracks to a private playlist requires the playlist-modify-private
scope.
this.spotifyService.addPlaylistTracks('user_id', 'playlist_id', 'comma separated string or array of spotify track uris');
Example:
this.spotifyService
.addPlaylistTracks('1176458919', '2TkWjGCu8jurholsfdWtG4', 'spotify:track:4iV5W9uYEdYUVa79Axb7Rh,spotify:track:1301WleyT98MSxVHPZCA6M')
.subscirbe(data => {
console.log('tracks added to playlist');
});
Remove one or more tracks from a user’s playlist. Removing tracks from a public playlist requires the playlist-modify-public
scope. Removing tracks from a private playlist requires the playlist-modify-private
scope.
this.spotifyService.removePlaylistTracks('user_id', 'playlist_id', 'comma separated string or array of spotify track ids or uris');
Example:
this.spotifyService
.removePlaylistTracks('1176458919', '2TkWjGCu8jurholsfdWtG4', 'spotify:track:4iV5W9uYEdYUVa79Axb7Rh, spotify:track:1301WleyT98MSxVHPZCA6M')
.subscirbe(data => {
console.log('tracks removed from playlist');
});
Reorder a track or a group of tracks in a playlist.
this.spotifyService.reorderPlaylistTracks('user_id', 'playlist_id', options);
Example:
this.spotifyService.reorderPlaylistTracks('1176458919', '2TkWjGCu8jurholsfdWtG4', {
range_start: 8,
range_length: 5,
insert_before: 0
}).subscirbe(data => {
console.log(data);
});
Replace all the tracks in a playlist, overwriting its existing tracks. This powerful request can be useful for replacing tracks, re-ordering existing tracks, or clearing the playlist. Replacing tracks in a public playlist requires the playlist-modify-public
scope. Replacing tracks in a private playlist requires the playlist-modify-private
scope.
this.spotifyService.replacePlaylistTracks('user_id', 'playlist_id', 'comma separated string or array of spotify track ids or uris');
Example:
this.spotifyService
.replacePlaylistTracks('1176458919', '2TkWjGCu8jurholsfdWtG4', 'spotify:track:4iV5W9uYEdYUVa79Axb7Rh, spotify:track:1301WleyT98MSxVHPZCA6M')
.subscirbe(data => {
console.log('tracks removed from playlist');
});
Change a playlist’s name and public/private state. (The user must, of course, own the playlist.) Changing a public playlist requires the playlist-modify-public
scope. Changing a private playlist requires the playlist-modify-private
scope.
this.spotifyService.updatePlaylistDetails('user_id', 'playlist_id', options);
Example:
this.spotifyService
.updatePlaylistDetails('1176458919', '2TkWjGCu8jurholsfdWtG4', { name: 'Updated Playlist Title' })
.subscirbe(data => {
console.log('Updated playlist details');
});
User needs to be logged in to gain access to user profiles
Get public profile information about a Spotify user.
this.spotifyService.getUser('user_id');
Example:
this.spotifyService.getUser('wizzler').subscirbe(data => {
console.log(data);
});
Get detailed profile information about the current user (including the current user’s username).
this.spotifyService.getCurrentUser();
Example:
this.spotifyService.getCurrentUser().subscirbe(data => {
console.log(data);
});
Get Spotify catalog information about artists, albums, or tracks that match a keyword string.
this.spotifyService.search('Search Query', 'type', options);
Example:
this.spotifyService.search('Nirvana', 'artist').subscirbe(data => {
console.log(data);
});
Get Spotify catalog information for a single track identified by its unique Spotify ID or Spotify URI.
this.spotifyService.getTrack('Track Id or Spotify Track URI');
Example:
this.spotifyService.getTrack('0eGsygTp906u18L0Oimnem').subscirbe(data => {
console.log(data);
});
Get Spotify catalog information for multiple tracks based on their Spotify IDs.
this.spotifyService.getTracks('Comma separated list or array of Track Ids');
Example:
this.spotifyService.getTracks('0eGsygTp906u18L0Oimnem,1lDWb6b6ieDQ2xT7ewTC3G').subscirbe(data => {
console.log(data);
});
Get a detailed audio analysis for a single track identified by its unique Spotify ID or Spotify URI.
this.spotifyService.getTrackAudioAnalysis('Track Id or Spotify Track URI');
Example:
this.spotifyService.getTrackAudioAnalysis('0eGsygTp906u18L0Oimnem').subscirbe(data => {
console.log(data);
})
Get audio feature information for a single track identified by its unique Spotify ID or Spotify URI.
this.spotifyService.getTrackAudioFeatures('Track Id or Spotify Track URI');
Example:
this.spotifyService.getTrackAudioFeatures('0eGsygTp906u18L0Oimnem').subscirbe(data => {
console.log(data);
})
Get audio features for multiple tracks based on their Spotify IDs.
this.spotifyService.getTracksAudioFeatures('Comma separated list or array of Track Ids');
Example:
this.spotifyService.getTracksAudioFeatures('0eGsygTp906u18L0Oimnem,1lDWb6b6ieDQ2xT7ewTC3G').subscirbe(data => {
console.log(data);
})
Get tracks from the current user’s recently played tracks. Requires the user-read-recently-played
scope.
this.spotifyService.getUserRecentlyPlayed(options);
Example:
this.spotifyService.getUserRecentlyPlayed().subscirbe(data => {
console.log(data);
});
Will open login window. Requires user to initiate as it will open a pop up window. Requires client id, callback uri and scope to be set in config.
this.spotifyService.login();
Example:
login() {
this.spotifyService.login();
};
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title></title>
<script>
window.onload = function () {
var hash = window.location.hash;
if (window.location.search.substring(1).indexOf("error") !== -1) {
// login failure
window.close();
} else if (hash) {
// login success
var token = window.location.hash.split('&')[0].split('=')[1];
localStorage.setItem('spotify-token', token);
}
}
</script>
</head>
<body>
</body>
</html>
import {Component} from '@angular/core';
import {SpotifyService} from './spotify.service';
@Component({
selector: 'my-app',
template: `
<h1>angular2-spotify</h1>
<button *ngIf="!user" (click)="login()">Login</button>
<p *ngIf="!!user">You are logged in as: {{user.display_name}}</p>
`,
providers: [
SpotifyService, {
provide: "SpotifyConfig",
useValue: {
clientId: 'ABC123DEF456GHfddId789JKL',
redirectUri: 'http://www.example.com/callback.html',
scope: 'user-read-private',
// If you already have an authToken
authToken: localStorage.getItem('angular2-spotify-token')
}
}
]
})
export class AppComponent {
private user: Object;
constructor(private spotifyService: SpotifyService) { }
login() {
this.spotifyService.login().subscribe(
token => {
console.log(token);
this.spotifyService.getCurrentUser()
.subscribe(data=> { console.log("getCurrentUser: ", data); this.user = data },
err=> console.error(err));
},
err => console.error(err),
() => { });
}
}
Check out my Playlist Manager for Spotify