我使用twitch.tv api并使用Angular $资源工厂。我尝试使用的端点是:GET / channels /:channel。我想要做的是获取每个数组元素的通道。我试过/频道/用户[1],但我知道这是错的。如何获取阵列中所有用户的:channel?或者有更好的方法吗?
(function() {
angular.module('twitch', ['ngResource'])
.controller('TwitchController', ['$scope', 'TwitchAPI', function($scope, TwitchAPI) {
$scope.getAPI = function(){
var users = ["ESL_SC2", "OgamingSC2", "cretetion", "freecodecamp", "storbeck", "habathcx", "RobotCaleb", "noobs2ninjas"];
for(var i = 0; i < 8; i++){
TwitchAPI.get({channel: users.i});
}
}
$scope.online = [];
$scope.offline = [];
}])
.factory('TwitchAPI', function TwitchAPIFactory($resource){
return $resource('https://api.twitch.tv/kraken/channels/:channel', { callback: "JSON_CALLBACK" });
});
})();
答案 0 :(得分:0)
首先,您不需要使用JSONP,因为Twitch API支持CORS请求,您可以像这样配置$resource
return $resource('https://api.twitch.tv/kraken/channels/:channel', {}, {
get: {
method: 'GET',
headers: {
Accept: 'application/vnd.twitchtv.v3+json',
'Client-ID': 'Your client ID'
}
}
})
如果你真的想使用JSONP,你就不能在请求中发送头信息,所以它必须看起来像
return $resource('https://api.twitch.tv/kraken/channels/:channel', {
callback: 'JSON_CALLBACK',
api_version: 3,
client_id: 'your client ID'
}, {
get: {
method: 'JSONP'
}
})
看起来不像是一次获得多个频道(参考:https://github.com/justintv/Twitch-API/blob/master/v3_resources/channels.md),但你应该能够并行实现这一目标
您可以像这样创建一个简单的承诺数组
var promises = users.map(user => TwitchAPI.get({channel: user}).$promise);
然后,您可以使用$q.all
$q.all(promises).then(channels => {
angular.forEach(channels, channel => {
// access each channel's properties here
console.log('Channel name:', channel.display_name);
});
});
不要忘记注入$q
服务。