2016-11-19 88 views
4

我創建了一個服務使用Web API控制器方法從數據庫中提取數據。但每當我注入的服務,並調用控制器的服務方法,它顯示了以下錯誤:

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

嘗試了很多,但無法理解哪裏錯了居然之所在!

這裏是我的AngularJS模塊代碼:

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

這裏是我的RouteConfig

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

這裏是我的服務:

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

這裏是我的AngularJS控制器

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

    }) 

在哪裏其實是錯誤的!任何幫助請!

+0

$ routeProvider.when( 「/產品/信息/:ID」, 並不像$ routeProvider..when(」/products/details /:id「, –

+0

哈哈!!這實際上不是問題!!這只是輸入錯誤:) – TanvirArjel

+0

」/ products/details /「+ id –

回答

6

有幾件事情,我想記下

  1. 你不能注入$scope內部服務
  2. 您應該返回從服務方法$http.get承諾進去控制器數據。
  3. 內部控制器使用.then從服務功能檢索數據。

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

太棒了!非常感謝清晰的插圖! – TanvirArjel

+0

@TanvirArjel謝謝,很高興知道:) –

+0

@Pankaj_Parkar,它顯示的產品沒有定義!錯誤!! – TanvirArjel

2

您不能將$ scope注入到服務中,因爲特定的作用域僅在指令和組件中可用。您只能使用$ rootScope

這實際上是有道理的,因爲服務是單身人士。當注入到多個控制器時,哪個$ scope應該角度使用呢? $ rootScope另一方面也是一個單身人士,所以工程。

+0

謝謝!如果您根據輸出重寫/更改我的代碼並將其作爲答案提交,那將非常棒! – TanvirArjel

+0

我會,但我在我的手機上。我想給你一個答案,所以你可以走了。 – Robba

相關問題