2016-06-01 2 views
1

저는 Angular를 통해 Instagram API를 사용하고 있습니다. 나는 인증없이 그것을 소비하고있다.콜백을 사용하지 않고 instagram API 호출

내 코드는 다음과 같습니다. 콜백을 사용하여이 API를 호출하는 가장 좋은 방법은 누구나 조언 할 수 있습니다. 약속을 사용하여 더 나은 접근법이 있습니까? 그렇다면 어떻게 보일까요? 또한이 코드에 오류 처리기를 추가하려면 어떻게해야합니까?

는 과거의, callbacks를 사용하지 마십시오

app.factory('socialMedia', ['$http', function($http){ 
    return { 
     fetchInstagram: function(callback){  
      var url = "https://api.instagram.com/v1/users/*******/media/recent?client_id=*****&callback=JSON_CALLBACK"; 
      $http.jsonp(url).success(function(response){ 
       callback(response.data); 
      }); 
     } 
    } 
}]); 

controller.js

app.controller("instagramCtrl", ["socialMedia", function (socialMedia) { 
    instagramCtrl = this; 
    this.instagramPosts = []; 
    this.loading = true; 

    socialMedia.fetchInstagram(function (data){ 
     instagramCtrl.loading = false; 
     for(var i = 0; i < 5; i++){ 
      instagramCtrl.instagramPosts.push(data[i]); 
     }   
    }); 
}]); 

답변

0

을 factory.js.

app.factory('socialMedia', ['$http', function($http){ 
    return { 
     fetchInstagram: function() {  
      var url = "https://api.instagram.com/v1/users/*******/media/recent?client_id=*****&callback=JSON_CALLBACK"; 
      return $http.jsonp(url).then(function(response) { 
       return response.data; 
      }); 
     } 
    } 
}]); 

당신이 fetchInstagram 방법에서 약속을 반환해야합니다 : $http 서비스 수익률은 훨씬 더 편리 옵션 (오류 처리, 약속 체인) 인 개체를 약속드립니다. 컨트롤러에서 다음

이 같이 사용할 것이다 :

socialMedia.fetchInstagram().then(function(data) { 
    $scope.data = data; 
}); 
+0

환호! 그게 내가 무엇을 찾고 있었는지 – phantom

+0

어떻게 fucntion이 컨트롤러에서와 같이 보일 것인가를 보여줄 수 있습니까? – phantom

+0

확실한 답변을 확인하십시오. – dfsq