TanvirArjel TanvirArjel - 14 days ago 7
AngularJS Question

AngularJS: Error: [$injector:unpr] Unknown provider: $scopeProvider <- $scope <- productService

I have created a Service to pull data from database using Web API controller method. But whenever I inject the service and call the service method in controller, it shows the following error:


Error: [$injector:unpr] Unknown provider: $scopeProvider <- $scope <- productService
http://errors.angularjs.org/1.5.8/$injector/unpr?p0=copeProvider%20%3C-%20%24scope%20%3C-%20productService


Tried a lot but cannot understand where the wrong actually lies!

Here is My AngularJS Module Code:

var app = angular.module("Demo", ["ngRoute"])


Here is my RouteConfig

app.config(function($routeProvider, $locationProvider) {
$routeProvider.when("/products/details/:id",
{
templateUrl: "Temaplates/details.html",
controller: "productDetailsController"
})
})


Here is My Service:

app.factory('productService',
function($scope, $http, $routeParams) {
return {
getDataById: function() {
alert("Hello I am invoked");
$http({
method: "GET",
url: "http://localhost:43618/api/Products",
params: { id: $routeParams.id }
})
.then(function(response) {
$scope.product = response.data;
})
}
};
});


Here is my AngularJS Controller

app.controller("productDetailsController", function ($scope, $http, $routeParams, $location, productService) {
$scope.message = "Product Details";
$scope.product = productService.getDataById();

})


Where is the wrong actually!! Any Help Please!!

Answer

There are several things which I wanted to note down

  1. You can't inject $scope inside service
  2. You should return $http.get promise from service method to get data inside controller.
  3. Inside controller use .then to retrieve data from service function.

Factory

app.factory('productService',
  function($http, $routeParams) {
    return {
      getDataById: function() {
            //return proimise from here
        return $http.get("http://localhost:43618/api/Products", {
            params: { id: $routeParams.id }
        });
      }
    };
});

Controller

app.controller("productDetailsController", function($scope, $http, $routeParams, $location, productService) {
    $scope.message = "Product Details";
    productService.getDataById().then(function(response){
      $scope.product = response.data;
    }, function(error){
      console.log("Error occured ", error);
    });
});
Comments