2016-08-02 4 views
0

나는 서비스가 여기 선언 :

(function() { 
    'use strict'; 

    angular 
     .module('ngInterview.api.students') 
     .service('StudentsService', StudentsService); 

    StudentsService.$inject = ['$http']; 
    function StudentsService($http) { 

     /** 
     * Exposed functions 
     */ 

     this.getName = getName; // This function serves no purpose. It's just here as an example. 

     this.getStudents = function() { 
      console.log("getting to the getStudents function"); 
      return $http.get("http://il-resume-api.azurewebsites.net/api/students").then(function(res) { 
       console.log("getting data back"); 
       console.log(res.data); 
       return res.data; 
      }, function(res) { 
       console.log("getting bad data"); 
       console.log(res); 
       return res.data; 
      }); 
     } 

     /** 
     * Implementations 
     */ 

     function getName() { 
      return 'studentsService'; 
     } 
    } 
})(); 

내 코드 만에 도달 몇 가지 이유를 들어 "를 getStudents 기능에 점점"그 후 응답하지 않습니다. 컨트롤러에서 $ http를 사용하여 빈 프로젝트를 설정하려고 시도했지만 작동하지만 엔드 포인트에서 데이터를 검색하지만 어떤 이유로이 서비스는 모듈의 일부로 사용되지 않습니다. 그리고 내가 console.log $ http 일 때 유효한 객체를 얻었으므로 그렇게 생각하지 않습니다.

+0

즉시 CONSOLE.LOG'후 (이하 "getStudents 기능에 점점");'을 함수에서 돌아 오는 중입니다. 콘솔에 대한 추가 인쇄는 HTTP 요청이 완료 될 때만 수행됩니다. 함수 내에서 http.get을 호출하고 함수 자체를 반환하십시오. – FDavidov

+0

'getStudents'를 약속으로 다루고 있습니까? '$ http'를 반환하면 getStudents 함수로'then'을 사용해야 만 결과를 기대할 수 있습니다. – AranS

답변

1

getStudents 함수가 $http.get을 반환합니다. 이렇게하면 getStudents 함수를 호출하는 사람에게 약속을 건네줍니다. 당신이 행동에 로깅을보고 싶다면, 다음과 같이, 그에 따라 기능을 치료 :

컨트롤러 범위

studentsService.getStudents().then(function() { 
    console.log("I expect to see my logs right above this log"); 
}) 
+0

하지만 컨트롤러가 처리하는 방법에 상관없이 여전히 내 console.log를 가져야합니다. 컨트롤러의 .then 문에 console.log를 넣었는지 확인하기 위해 아무 것도 얻지 못했습니다. :/ –

+0

함수가 약속을하고 예상했던대로 돌아 왔을 때만 로그를 볼 수 있습니다. 컨트롤러의 로직을 보여줄 수 있습니까? – AranS