我對角度有點新,我正在摸索這個問題。我的工廠console.log
顯示,第一次通過一切正確定義,但工廠出於某種原因重新評估數據,我將它傳遞到undefined
。這裏是我的代碼開始是將數據傳遞給控制器,然後到工廠HTML輸入:AngularJS Ajax獲取問題
HTML:
<input type="text" placeholder="Enter Channel" ng-model="channel" ng-keydown="$event.which === 13 && cname(channel)"/>
這將發送到我的控制器是什麼在輸入字段中鍵入一次輸入鍵被按下cnam(channel)
控制器和工廠:
angular.module('youtubePlaylistAppApp')
.factory('ytVids', function($http){
return{
getChannel: function(name){
console.log('name: '+name);
var url = 'https://www.googleapis.com/youtube/v3/channels?part=contentDetails&forUsername='+ name +'&key=[my api key]';
console.log(url);
return $http.get(url);
},
getVids: function(channel){
console.log('channel: '+ channel);
return $http.get('https://www.googleapis.com/youtube/v3/playlistItems?part=snippet%2CcontentDetails&maxResults=50&playlistId='+channel+'&key=[my api key]')
.success(function(response){
//console.log(response.items);
return response.items;
});
}
};
})
.controller('indexCtrl', function ($scope, ytVids) {
$scope.cname = function(channel){
console.log(channel);
ytVids.getChannel(channel);
ytVids.getChannel().success(function(response){
console.log(response);
console.log(response.items[0].contentDetails.relatedPlaylists.uploads);
ytVids.getVids(response.items[0].contentDetails.relatedPlaylists.uploads)
.success(function(data){
console.log(data.items);
$scope.ytChannel = data.items;
});
});
};
});
這裏是我進入後看到我的控制檯開發工具的輸出在輸入字段中輸入時按下:
第一個控制檯日誌console.log(channel);
控制檯記錄正確的響應。如果鍵入「freddiew」並回車,也就是登錄
然後,我傳遞到我廠ytVids.getChannel(channel);
和控制檯登錄工廠console.log('name: '+name);
這記錄正確的響應,在name: freddiew
我再聲明可變var url =
,並給它YouTube網址,並與URL
我那麼控制檯日誌的變量,並得到期望是什麼https://www.googleapis.com/youtube/v3/channels?part=contentDetails&forUsername=freddiew&key=[my api key]'
該網址的作品時,我在郵遞員已經嘗試過了,Concat的頻道名稱只是硬編碼的名字,但通過名稱,控制檯然後吐出一些更多的日誌,我不知道爲什麼,它看起來像它覆蓋了我剛剛建立的網址,因爲這是從什麼記錄工廠:
name: freddiew
https://www.googleapis.com/youtube/v3/channels?part=contentDetails&forUsername=freddiew&key=[my key]
它然後在此之後記錄爲undefined
和API調用concats undefined
的URL,使API調用與此undefined
網址
name: undefined
https://www.googleapis.com/youtube/v3/channels?part=contentDetails&forUsername=undefined&key=[my key]
forUsername=
是在該通道的名稱應該去。
有人知道爲什麼它被定義爲undefined
?
我沒有意識到!感謝您的參與。這將是有道理的,爲什麼它被稱爲兩次.... – Chipe
@Chipe高興地幫助你,謝謝:-) –