2016-06-18 3 views
0

안녕 친구 나는 새로운 각도로 서비스에서 컨트롤러로 데이터를 호출하는 방법을 알아 냈습니다. 콘솔 Error: [$injector:unpr] Unknown provider: $scopeProvider <- $scope <- productlist 나에게 오류를 제공각도 1.5를 사용하는 컨트롤러에서 서비스 데이터를 호출하십시오.

data.json 아래

[{ 
    "brandname" : "VU", 
    "image" : "images/1.jpeg", 
    "detail" : "Vu 102cm (40) Full HD LED TV", 
    "price": "20,000", 
    "productId" : "001" 

},{ 
    "brandname" : "Micromax", 
    "image" : "images/52.jpeg", 
    "detail" : "Micromax 81cm (31.5) HD Ready LED", 
    "price": "12,489", 
    "productId" : "052" 

}] 

contoller.js 언급 코드 위

var appProduct = angular.module('assignment', []); 

appProduct.service('productlist', ['$scope', function($scope){ 
    $http({method : 'GET',url : 'js/data.json'}) 
      .success(function(data, status) { 
       $scope.items = data; 
       //console.log(data) 
      }) 
      .error(function(data, status) { 
       alert("Error"); 
      }); 
     setTimeout(function(){ 
      $scope.$apply(); 
     },1); 
}]) 



appProduct.controller('productGrid', function($scope, $http, productlist){ 

    $scope.item = productlist.items; 
    console.log(productlist.items) 

}) 

을 내 코드를 확인하시기 바랍니다. 제발 도와주세요

답변

1

$scope을 서비스에 삽입 할 수 없습니다. 컨트롤러에만 바인딩 할 수 있기 때문입니다. 서비스가 끝나면 컨트롤러에서 $scope.$apply()을 호출해야합니다.

는 또한 - "성공"및 "오류"방법의 they're deprecated을 제거 :

The $http legacy promise methods success and error have been deprecated. Use the standard then method instead. If $httpProvider.useLegacyPromiseExtensions is set to false then these methods will throw $http/legacy error.

코드는해야 다음과 같습니다

var appProduct = angular.module('assignment', []); 

appProduct.service('productlist', ['$http', function($http) { 
    return { 
     getProducts: function() { 
      return $http.get('js/data.json') 
       .then(function(response) { 
        return response.data; 
       }, function() { 
        return "Error while fetching data"; 
       }); 
     } 
    } 
}]); 



appProduct.controller('productGrid', ['$scope', '$http', '$timeout', 'productlist', function($scope, $http, $timeout, productlist) { 
    productlist.getProducts().then(function(data) { 
     $timeout(function() { 
      $scope.items = data; 
     }); 
    }, function(data) { 
     console.log(data); 
    }); 
}]); 

다음은이 작업의 Plunker은 다음과 같습니다 Plunker

서비스가 $http 호출에서 약속을 반환합니다. 그런 다음 컨트롤러에서 데이터를 분석하고 범위를 조작 할 수 있습니다.

+0

도움을 주셔서 감사합니다.하지만 코드를 사용한 후에도 여전히 '오류 : $ http가 정의되지 않았습니다'라는 오류가 발생합니다 ... 제발 – Kamal

+0

@ 카말, 오, 내 잘못, 나는 서비스에'$ http'를 주입하는 것을 잊었다. 코드를 수정했습니다. – itachi

+0

ok ..하지만 콘솔에서'productlist가 함수가 아닙니다. '( – Kamal

0

@ Kamal, 귀하의 서비스에 $ http를 (를) 주입해야합니다. 서비스에서 $ scope를 제거 할 수 있습니까? 종속성이 정의되어 있는지 확인하고 문제를 해결할 것입니다

관련 문제