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

I created a service to retrieve data from a database using the Web API method. But whenever I deploy the service and call the service method in the 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

I tried a lot, but could not understand where the lie really lies!

Here is my AngularJS module module:

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 it really wrong? Any help please!

+4
2

,

  • $scope
  • $http.get , .
  • .then .

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 }
        });
      }
    };
});

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);
    });
});
+6

$scope , . $rootScope

, . , $scope angular? $rootScope, , , .

+2

Source: https://habr.com/ru/post/1661277/


All Articles