2013-10-29 70 views
1

我在查詢數據的YouTube API後遇到問題。這個問題在這個jsfiddle中複製,以防你想嘗試它jsfiddle.net/YBvQJ/4/AngularJS不會更新從承諾返回的數組

問題如下:第一次搜索結果顯示正確。但是,如果我執行第二次搜索,即使搜索已正確執行,結果也不會在視圖中更新。

我有一個服務,使用$ http調用youtube API來執行給定參數的搜索。返回值是一個承諾:

.service('youTubeSearchService', ['$log', '$http', '$q', ($log, $http, $q) -> 
    apiKey = 'myApiKey' 
    url = 'https://www.googleapis.com/youtube/v3/search' 
    deferred = $q.defer() 
    return service = 
    search: (query) -> 
     $http.get(url, params: { 
      key: apiKey 
      type: 'video' 
      maxResults: '6' 
      part: 'id,snippet' 
      fields: 'items/id,items/snippet/title' 
      q: query 
     }) 
     .success (data) -> 
     $log.info "In success" 
     $log.info data 
     deferred.resolve data.items.map (item) -> 
      videoId: item.id.videoId 
      title: item.snippet.title 
     .error (data) -> 
     $log.info "In error" 
     $log.info data 
     deferred.reject data 
     return deferred.promise 
]) 
.config(['$httpProvider', ($httpProvider) -> 
    # Disable this header or the youtube API won't work 
    delete $httpProvider.defaults.headers.common['X-Requested-With'] 
]) 

該服務在控制器中使用這樣的:

.controller('SearchCtrl', ['$log', '$scope', 'youTubeSearchService' 
    , ($log, $scope, youTubeSearchService) -> 
     $scope.search = -> 
     $scope.results = youTubeSearchService.search($scope.query) 
    ]) 

的數據視圖中使用這樣的:

<input type="text" ng-model="query" value="ejemplo"> 
<button ng-click="search()">Search in YouTube</button> 
<li ng-repeat="item in results"> 
    <p><a target="blank" href="//www.youtube.com/watch?v={{item.videoId}}"> 
     {{item.title}} 
    </a></p> 
</li> 

我有將日誌調用放入服務中以顯示youtube API返回一個新數組。

我認爲這個問題可能與範圍沒有在視圖中更新有關。不應該這樣,因爲承諾會調用$ digest循環,ng-click指令也會這樣。

幫助將不勝感激!先謝謝你。

回答

3

您的搜索正在返回服務承諾。因此,您將$scope.results設置爲承諾。

$scope.results = youTubeSearchService.search($scope.query) 

相反,你應該處理的承諾,並設置結果:

youTubeSearchService.search($scope.query).then(function(results) { 

    $scope.results = results;  
}, function(error) { 

    $scope.error = error; 
}); 

在CoffeeScript的:

youTubeSearchService.search($scope.query).then ((results) -> 
    $scope.results = results 
), (error) -> 
    $scope.error = error 
+1

加入咖啡爲你 – jcollum

+0

@jcollum謝謝! –