[英]Angular JS: Error: [$injector:unpr] Unknown provider: $scopeProvider
[英]AngularJS: Error: [$injector:unpr] Unknown provider: $scopeProvider <- $scope <- productService
我創建了一個服務 ,使用Web API控制器方法從數據庫中提取數據。 但每當我注入服務並在控制器中調用服務方法時,它都會顯示以下錯誤:
錯誤:[$ injector:unpr]未知提供者:$ scopeProvider < - $ scope < - productService http://errors.angularjs.org/1.5.8/ $ injector / unpr?p0 = copeProvider%20%3C-%20% 24scope%20%3 C-%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();
})
實際上錯在哪里!! 任何幫助請!!
有幾件事我想記下來
$scope
$http.get
promise以獲取控制器內的數據。 .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);
});
});
您不能將$ scope注入服務,因為特定的范圍僅在指令和組件中可用。 您只能使用$ rootScope
這實際上是有道理的,因為服務是單身人士。 當注入多個控制器時,哪個$ scope應該角度使用呢? 另一方面,$ rootScope也是一個單例,因此有效。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.