2014-03-19 70 views
1

我有兩個$ http查詢鏈接在一起。第一個從第三方API獲取藝術家姓名,然後使用AngularJS填充第二個$ http查詢中的查詢URL,這將從獲得另一個第三方API的封面。

我發現的問題是,當搜索以「THE」開頭的藝術家姓名(例如The Smiths)時,第一個API將以「Smiths,The」響應,這將不會被第二個API作爲藝術家的名字。

既然如此,是否有某種方式行事uppon,藝術家名稱收到結束與的情況下「將」,並解析其進入第二$ HTTP查詢之前改變它?

下面是相關代碼:

$scope.getDetails = function (id) { 
    $http.get('http://api.discogs.com/artists/' + id). 
    success(function(data) { 
     $scope.artist = data; 
    }); 
    $http.get('http://api.discogs.com/artists/' + id + '/releases?page=1&per_page=12'). 
    success(function(data2) { 
     $scope.releases = data2.releases; 
    }); 
    $scope.clicked = true; 
    $scope.sliding = true; 
} 
} 
function ImageCtrl($scope, $http) { 
     $scope.image = 'img/record-default.png'; 
     $http.get('http://ws.audioscrobbler.com/2.0/?method=album.getinfo&api_key=e8aefa857fc74255570c1ee62b01cdba&artist=' + $scope.artist.name + '&album=' + $scope.release.title + '&format=json'). 
     success(function (data4) { 
      $scope.image = data4.album.image[2]['#text']; 
     } 
    ); 
}; 
+1

如果你使用[promises](http://docs.angularjs.org/api/ng/service/$q)並鏈接它們,你應該能夠在做之前改變藝術家的名字你的第二個查詢。一個示例鏈接在http://stackoverflow.com/questions/18010796/return-interdependent-async-promises-in-routeprovider-resolve – miqid

+0

真的沒有辦法分析字符串和修改它之前傳遞到下一個網址而不改變整個代碼結構? :S –

+1

您可以嘗試在'$ scope.artist'上使用'$ scope。$ watch',以便每當它發生變化時(即通過HTTP請求),您都可以在watch回調中進行處理,以適當修改藝術家名稱。我舉了一個例子來說明我的意思 - http://jsfiddle.net/QBz2R/ – miqid

回答

1

複製我的評論到一個答案,因爲它似乎有幫助。

我對所問問題的建議是觀察從HTTP請求返回的數據,然後根據需要對手錶回調中的任何數據字段進行適當調整。

$scope.$watch(function() { 
    return $scope.artist; 
}, function() { 
    var pos = $scope.artist.name.toLowerCase().indexOf(', the'); 
    if (pos != -1) { 
     $scope.artist.name = 'The ' + $scope.artist.name.slice(0, pos); 
    } 
}); 

如果使用大量的順序,相互依存的HTTP請求,但後來發現自己,我不建議使用的承諾,而不是鏈接。 :-)