2017-05-11 7 views
2

내 NodeJS API/MongoDB 엔드 포인트에서 일부 JSON을 가져올 컨트롤러와 서비스를 설정했습니다.angularJs의 요청 응답 응답

내 브라우저 콘솔에서 반환 된 개체와 5 개 항목을보고 내 API를 쿼리 할 때 브라우저에서 동일한 json을 볼 수 있으므로 서버 측에서 작동하는 것으로 알고 있습니다.

왜 NG를 시도 할 때 페이지에 아무 것도 표시되지 않고 다시 시도 할 때 혼란 스럽습니다. 반환 된 데이터를 로그 아웃 할 때 다시 정의되지 않습니다.

저는 HTTP 모듈을 처음 사용하고 컨트롤러에서 사용하는 대신 DB 호출을 서비스로 리팩토링하려고합니다.

--- 컨트롤러 코드 ---

vm.getDepartments = function() { 
     vm.departments = DbService.getAllDepartments(); 
     console.log(vm.departments); 

    }(); 

--- 서비스 코드는 ---

function getAllDepartments() { 
     $http.get('/api/departments').then(function(err, response) { 
      if (err) { 
       console.log(err); 
      } 
      return response; 

     }); 
    }; 

--- HTML 페이지를 --- ($ HTTP 사용)

<tbody> 
        <tr ng-repeat='dept in vm.departments'> 
         <td>{{ dept.departmentLong }}</td> 
         <td>{{ dept.departmentShort }}</td> 
         <td> 
          <button class='btn btn-warning'><span class='glyphicon glyphicon-edit'></span></button> 
          <button class='btn btn-danger' ng-click='vm.deleteDepartment(dept);'><span class='glyphicon glyphicon-ban-circle'></span></button> 
         </td> 
        </tr> 
       </tbody> 

답변

3

데이터를 얻을 수 response.data를 사용합니다.

then() 메서드는 response 개체로 호출 될 successerror 콜백이라는 두 인수를 사용합니다.

then() 메서드를 사용하면 에 callback 함수를 연결하십시오.

당신은 약속을 반환하는 함수를 만들 수 있도록 언급 @sachila의 ranawaka로하는 약속을 반환 mine.

$http.get('/api/departments')에 의해 게시 된 오래된 대답 보라. I은 위에서 언급

컨트롤러 사용시
function getAllDepartments() { 
    return $http.get('/api/departments') 
}; 

에게 다음 방법.

DbService.getAllDepartments().then(function(response) { 
     vm.departments = response.data; 
     console.log(vm.departments); 
},function(error){ 
     console.log(err); 
}); 

다른 방법은 callback 함수를 생성하고, getAllDepartments 방법으로 전달하는 것이다.

function getAllDepartments(callback) { 
    $http.get('/api/departments').then(function(response) { 
     callback(response); 
    }); 
}; 

컨트롤러 코드 : 또한 언급 할 가치가있다

vm.getDepartments = function() { 
    vm.departments = DbService.getAllDepartments(function(result){ 
     console.log(result); 
    }); 
}(); 
+0

이 그 (오류로 인해 발생)이 약속을 거부하면 $에 .catch() 메소드를 호출 할 수 있습니다를 처리하기위한 http.get ('/ api/departments'). – henktenk

+1

감사합니다. 당신의 설명이 매우 도움이되었습니다. 이제 작동 중이고 서비스에 대한 책임이 조금 더 있습니다. 약속은 저에게 도전이었습니다. 연습이 도움이 될 것입니다. –

2

은 http 요청을 반환합니다.

function getAllDepartments() { 
     return $http.get('/api/departments') 
}; 

그리고 컨트롤러 내부에서 약속을 잡으십시오. 당신이 잘못 then 방법을 사용

vm.getDepartments = function() { 
     DbService.getAllDepartments().then(function(response) { 

      vm.departments = response.data; 
      console.log(vm.departments); 
     }); 

    }