我正在使用名为xinranxiao:spotify-web-api的spotify web api包装程序包。我可以根据文本输入,使用服务器和客户端上的方法和调用返回相册列表。
我正在尝试使用两种方法,一种用于搜索本身,另一种用于将相册轨道与每个搜索结果联系起来。对我来说问题是JSON结果是独立的,我需要从专辑搜索中获取ID数组,并通过第二种方法传递它们。我不知道如何提取阵列,甚至不确定我是否朝着正确的方向前进。到目前为止,这是我的代码。下面的代码实际上是有效的,除了它显然为所有返回的专辑带来了相同的曲目。我怀疑我的大部分问题都是缺乏解析json的知识。任何帮助,将不胜感激。提前致谢。
- 在服务器上
Meteor.methods({
searchAlbums: function(query) {
var spotifyApi = new SpotifyWebApi();
//grab JSON list of albums based on text search
var response = spotifyApi.searchAlbums(query, {
limit: 50
});
// Need to refresh token
if (checkTokenRefreshed(response, spotifyApi)) {
response = spotifyApi.searchAlbums(query, {
limit: 50
});
}
return response.data.body;
},
fetchTracks: function(id) {
var spotifyApi = new SpotifyWebApi();
//grab JSON list of tracks based on album id
var response = spotifyApi.getAlbum(id);
// Need to refresh token
if (checkTokenRefreshed(response, spotifyApi)) {
response = spotifyApi.getAlbum(id);
}
return response.data.body;
}
});
var checkTokenRefreshed = function(response, api) {
if (response.error && response.error.statusCode === 401) {
api.refreshAndUpdateAccessToken();
return true;
} else {
return false;
}
};
- 在客户端
Template.spotify.events({
'click .submit': function(e, template) {
var albumName = $('.albumName').val();
//temporary to get key/values from JSON
var albumId = '4v7ImrdxXL4rYPutcdmyXV';
Meteor.call('searchAlbums', albumName, function(err, response) {
Session.set('album', response.albums.items);
console.log(response);
});
Meteor.call('fetchTracks', albumId, function(err, response) {
Session.set('albumTracks', response.tracks.items);
console.log(response);
});
}
});
- 模板
<template name="spotify">
{{> loginButtons}}
<h3>Search for albums with a specified word</h3>
<div class="track__search">
<input class="albumName" data-source="searchAlbums" name="search" placeholder="Search albums" tabindex="1" type="text" />
<input class="submit" name="submit" type="submit" />
</div>
<div class="track__results">
{{# each $.Session.get 'album' }}
<div class="track">
<div class="thumb">
<img src="{{ images.[0].url }}" />
</div>
<div class="name">
<strong>Album Name:</strong>
<a href="{{ external_urls.spotify }}" target="_blank">{{ name }}</a>
<div class="albumId" data-album-id="{{ id }}">{{ id }}</div>
<br/>
<strong>AlbumTracks:</strong>
<ol>
{{# each $.Session.get 'albumTracks' }}
<li>
{{ name }}
</li>
{{/each}}
</ol>
</div>
</div>
{{/each}}
</div>
</template>
答案 0 :(得分:0)
您可以在 searchAlbums 方法的响应后调用 fetchTracks 方法。
在客户端。
var albumId = '';
Meteor.call('searchAlbums', albumName, function(err, response) {
if(response){
Session.set('album', response.albums.items);
//You will need to update this to get all the albums tracks
albumId = response.albums.items[0].id;
Meteor.call('fetchTracks', albumId, function(err, response) {
Session.set('albumTracks', response.tracks.items);
console.log(response.tracks.items);
});
}
});