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!!
There are several things which I wanted to note down
$scope
inside service$http.get
promise from service method to get data inside controller..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);
});
});
You can't inject $scope into a service as specific scopes are only available in directives and components. You can only use $rootScope
This actually makes sense because a service is a singleton. When injected into multiple controllers, which $scope should angular use then? $rootScope on the other hand is also a singleton so that works.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With