在AngularJS中使用$ http.get撤消JSON时出错400

时间:2016-04-29 09:30:43

标签: javascript angularjs json http

当我尝试使用$ http.get从此URL检索JSON时,我收到错误400。

$http.get('https://api.spotify.com/v1/search?q=artist:Owl+City+title:On+The+Wing&type=track&limit=1').
  success(function(data) {
    console.log("Success");         
  })
    .error(function(error, status, headers, config) {
      console.log(status);
      console.log("Error occured");
    });

我设法用这个检索它:

$.getJSON('https://api.spotify.com/v1/search?q=artist:Owl+City+title:On+The+Wing&type=track&limit=1').then(function (data) { console.log("Success");});

但问题是,当我尝试使用此方法更改$ scope中的值时,它仅显示在视图中,之后有一个动作,因为我得到了上一首歌曲而不是当前的歌曲信息

这是控制器代码:

 angular.module('pwilApp')
  .controller('SongsCtrl', function ($rootScope, $scope,$http,$sce) {
    var increment = 0;
    var laSimilaire = "";
    var init = true;

    $rootScope.activeHome = "";
    $rootScope.activeSongs = "active";
    $rootScope.activeAccount = "";
    $rootScope.activeContacts = "";
    $rootScope.activeAbout = "";
    $rootScope.activeConnection = "";
    $scope.currentPage = 1;
    $scope.totalPages = 0;
    $scope.loading = true;

    $scope.$on('$viewContentLoaded', function () {
      $http.get('https://api.spotify.com/v1/search?q=artist:Owl+City+title:On+The+Wing&type=track&limit=1').success(function (data) {
          console.log("Success");              
        })
        .error(function (error, status, headers, config) {
          console.log(status);
          console.log("Error occured");
        });

      $.getJSON('https://api.spotify.com/v1/search?q=artist:Owl+City+title:On+The+Wing&type=track&limit=1').then(function (data) {
        $scope.preview_url = $sce.trustAsResourceUrl(data.tracks.items[0].preview_url);
      });

    });

  }

谢谢你的回复。

1 个答案:

答案 0 :(得分:1)

作品非常适合我

 angular.module('pwilApp',[])
  .controller('SongsCtrl', function ($rootScope, $scope,$http) {
    var increment = 0;
    var laSimilaire = "";
    var init = true;

    $rootScope.activeHome = "";
    $rootScope.activeSongs = "active";
    $rootScope.activeAccount = "";
    $rootScope.activeContacts = "";
    $rootScope.activeAbout = "";
    $rootScope.activeConnection = "";
    $scope.currentPage = 1;
    $scope.totalPages = 0;
    $scope.loading = true;

      $http.get('https://api.spotify.com/v1/search?q=artist:Owl+City+title:On+The+Wing&type=track&limit=1').success(function (data) {
          console.log("Success",data);     
$scope.songData = data.tracks.items;         
        })
        .error(function (error, status, headers, config) {
          console.log(status);
          console.log("Error occured");
        });

  });
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="pwilApp" ng-controller="SongsCtrl">

<div ng-repeat="song in songData">
 {{song.id}} | {{song.name}}
</div>