我是angularJS的新手,我在下面的代码中遇到了一些问题。基本上我想要实现的是搜索一个术语的spotify API并检索给我的第一个播放列表,然后获取播放列表的URI并将其连接到一个嵌入的URL以显示在页面中。 / p>
我似乎无法让$ scope.spotifySearch对象以字符串格式进入$ scope.playlisturi范围。任何帮助将不胜感激。
app.controller('MainCtrl', function ($scope, $sce, Spotify) {
$scope.spotifySearch = Spotify.search('Top 40', 'playlist').then(function (data) {
return (data.playlists.items[0].uri);
});
$scope.trustSrc = function(src) {
return $sce.trustAsResourceUrl(src);
}
$scope.playlisturlfragment = "https://embed.spotify.com/?uri=";
$scope.playlisturi = $scope.spotifySearch;
$scope.playlisturl = {src:$scope.playlisturlfragment+$scope.playlisturi}
});
答案 0 :(得分:2)
您正在为spotifySearch
分配承诺,我认为您想要的是搜索返回的uri
。
这个问题基本上有两种方法。
playlisturl
。playlisturl
时,将值分配给spotifySearch
。这是第一种方法。
$scope.playlisturlfragment = "https://embed.spotify.com/?uri=";
Spotify.search('Top 40', 'playlist').then(function (data) {
$scope.playlisturl = {src:$scope.playlisturlfragment+data.playlists.items[0].uri}
});
另一种方法是观看spotifySearch
进行更改。
$scope.playlisturlfragment = "https://embed.spotify.com/?uri=";
Spotify.search('Top 40', 'playlist').then(function (data) {
$scope.spotifySearch = data.playlists.items[0].uri;
});
$scope.$watch('spotifySearch',function(value) {
if(!value) return;
$scope.playlisturl = {src:$scope.playlisturlfragment+value};
});
答案 1 :(得分:1)
您为$scope.spotifySearch
分配了承诺,而不是真实数据($http
返回承诺)。相反,你可以这样做:
app.controller('MainCtrl', function ($scope, $sce, Spotify) {
$scope.playlisturlfragment = "https://embed.spotify.com/?uri=";
$scope.playlisturl = {
src: ""
}
$scope.spotifySearch = Spotify.search('Top 40', 'playlist').then(function (data) {
// use the callback to assign the uri to your object
$scope.playlisturl.src = $scope.playlisturlfragment + data.playlists.items[0].uri;
});
});
答案 2 :(得分:0)
Angular使用承诺请求。这个承诺是异步的,很快就会返回值而不起作用。为此,使用回调函数:
app.controller('MainCtrl', function ($scope, $sce, Spotify) {
$scope.trustSrc = function(src) {
return $sce.trustAsResourceUrl(src);
};
$scope.init = function(){
$scope.search(function(uri){
$scope.playlisturlfragment = "https://embed.spotify.com/?uri=";
$scope.playlisturl = {src:$scope.playlisturlfragment + uri};
});
};
$scope.search = function(callback){
$scope.spotifySearch = Spotify.search('Top 40', 'playlist').then(function (data) {
callback(data.playlists.items[0].uri);
});
};
});
运行init方法以查看此示例