我创建了一个名为trailers
的表格。此表有两列,movie_id
和link
列。
我已经创建了一个JSONP函数来获取我想要保存到表中的数据,
service.trailer = function(youtube_link){
return httpPromise(
baseUrl + youtube_link + '/videos?api_key=a8f7039633f2065942cd8**8d7cadad4&callback=JSON_CALLBACK'
)
};
这是请求的JSONP输出,
{"id":157336,"results":[
{"id":"53db3c790e0a26189a000d09","iso_639_1":"en","key":"ePbKGoIGAXY","name":"Trailer 3","site":"YouTube","size":1080,"type":"Trailer"},
{"id":"550df44b9251413554004d43","iso_639_1":"en","key":"KlyknsTJk0w","name":"Own it today","site":"YouTube","size":720,"type":"Trailer"},
{"id":"533ec6fcc3a3685448009ccc","iso_639_1":"en","key":"nyc6RJEEe0U","name":"Teaser","site":"YouTube","size":720,"type":"Trailer"},
{"id":"5376ab510e0a26141c0005a8","iso_639_1":"en","key":"zSWdZVtXT7E","name":"Trailer","site":"YouTube","size":720,"type":"Trailer"},
{"id":"545da247c3a3685362005187","iso_639_1":"en","key":"Lm8p5rlrSkY","name":"Trailer 2","site":"YouTube","size":1080,"type":"Trailer"}
]}
以上数据来自电影Interstellar,它有5个对象。现在我想从每个对象中取出key
值并将其保存在我的trailer
表中,并带有相应的movie_id,在此示例中为157336
。我正在使用带有SQLite数据库的Ruby on Rails后端。
我想我需要使用forEach
并遍历每个结果并使用create函数将数据保存在表中。像这样的东西,
movieAdd.trailer(movie.id)
.then(function(response){
$scope.youtubeTrailer = [];
angular.forEach(response.results, function(item){
if (item.hasOwnProperty('key')) {
console.log ('Loop through results.')
}
})
这个forEach
函数现在遍历每个值,但我不知道如何在我的数据库中获取数据。
答案 0 :(得分:0)
最后我用了这个,
angular.forEach(response.results, function(item){
$scope.youtubeTrailer = [];
$scope.youtubeTrailer.push(item.key);
// console.log ($scope.youtubeTrailer)
var youtubeLink = $scope.youtubeTrailer.toString();
createTrailer.create({
link: youtubeLink,
movie_id: $scope.movieListID.id
})
})
我创建了一个forEach,它将item.key
插入到youtubeTrailer范围内,然后是一个create函数,然后再次循环。从清除youtubeTrailer范围开始。