无法在Angular中注入我的服务解析路由器配置

时间:2017-04-10 16:42:01

标签: angularjs angular-routing angular-services

(我的plunkr代码位于http://plnkr.co/edit/6KU3GblQtMdRAx3v3USV?p=preview

我正在尝试创建一个搜索栏(在导航中),该栏最终会打到后端REST API。单击输入' alpha'时输入搜索按钮。会触发到products / search / 0的路线?searchtext = alpha

单击该按钮会触发路径更改,该路径更改应按以下方式解决:

.when("/products/search/:page", {
        templateUrl: "products.html",
        controller: "ProductsSearchController",
        resolve: {
            // Define all the dependencies here
            ProdSearchServ : "ProdSearchService",
            // Now define the resolve function
            resultData : function(ProdSearchServ) {
                return ProdSearchServ.searchProducts();
            }
        }
    })

但是,我收到以下错误

  

angular.js:9784错误:[$ injector:unpr]未知提供者:ProdSearchServProvider< - ProdSearchServ

我相信我按照惯例做了大部分事情,可能是我在这里遗漏了什么?

我正在下面复制 script.js 代码(也在上面的plnkr链接中)。它具有所有路由配置和定义的控制器。

(function(){


// jargoViewer Create a new Angular Module 
// This would go into the html tag for index.html
var app = angular.module("jargoViewer", ["ngRoute"]);

app.config(function($routeProvider){
    $routeProvider
        .when("/main", {
            templateUrl: "main.html",
            controller: "NavController"
        })
        .when("/products/search/:page", {
            templateUrl: "products.html",
            controller: "ProductsSearchController",
            resolve: {
                // Define all the dependencies here
                ProdSearchServ : "ProdSearchService",
                // Now define the resolve function
                resultData : function(ProdSearchServ) {
                    return ProdSearchServ.searchProducts();
                }
            }
        })
        .otherwise({redirectTo:"/main"});
});

}());

// Nav Controller
(function() {
var app = angular.module("jargoViewer");

var NavController = function($scope, $location) {
    // Function to invoke the Prod search based on input 
    $scope.search = function() {
        console.log("searchText : " + $scope.searchtext);
        $location.path("products/search/0").search({searchtext: $scope.searchtext});
    };
};

app.controller("NavController", NavController);

}());

// Define the Prod Search Service here
(function() {
// Get reference to the app
var app = angular.module("jargoViewer");

// Create the factory
app.factory('ProdSearchService', function($routeParams, $http, $q) {

    var searchProducts = function() {
        pageNum = 0;
        searchParam = '';
        if (('page' in $routeParams) && (typeof $routeParams.page === 'number')) {
            pageNum = $routeParams.page;
        } 
        // Check if the router Param contains the field searchtext, if so, check if its a string
        if (('searchtext' in $routeParams) && (typeof $routeParams.searchtext === 'string')) {
            searchParam = $scope.routeParam.searchtext;
        }

        // Now make the http API hit to fetch the products
        var request = $http({
            method: "get",
            url: "http://abcd.com/products/search/" + pageNum,
            params: {
                search: searchParam
            },
         });
        return(request.then(handleSuccess, handleError));
    };

    function handleError(response) {
        // The API response from the server should be returned in a
        // nomralized format. However, if the request was not handled by the
        // server (or what not handles properly - ex. server error), then we
        // may have to normalize it on our end, as best we can.
        if (
            ! angular.isObject(response.data) ||
            ! response.data.message
            ) {
            return($q.reject( "An unknown error occurred."));
        }
        // Otherwise, use expected error message.
        return($q.reject(response.data.message));
    }

    // I transform the successful response, unwrapping the application data
    // from the API response payload.
    function handleSuccess(response) {
        if(response.data.error == true) {
           return($q.reject(response.data.message));
        }
        return(response.data.data);
    }

    return {
        searchProducts : searchProducts
    };
});
}());

// Define the Products Search Controller below
(function() {

var app = angular.module("jargoViewer");

//var ProductController = function($scope) {
var ProductsSearchController = function($scope, $routeParams, ProdSearchService) {
  // Nothing to do really here
};

app.controller("ProductsSearchController", ProductsSearchController);

}());

2 个答案:

答案 0 :(得分:1)

这是由您奇怪的命名惯例引起的。有时为ProdSearchServ,有时为ProdSearchService

如果您只选择一个并且一直使用它,那么您将不会遇到这些类型的错误。

Fixed Plunker

特别是您使用名称ProdSearchService创建服务,然后尝试使用其他名称:

app.factory('ProdSearchService',
//vs
resultData : function(ProdSearchServ) {

我想你,我们认为这段代码会为你修复它。但是,这仅适用于传递给控制器​​的依赖项,而不适用于通常的函数。对于已经存在的服务,您不需要像这样特别定义它们;而只是在控制器中使用正确的名称。

// Define all the dependencies here
ProdSearchServ : "ProdSearchService",

答案 1 :(得分:0)

我认为你说

时不需要定义依赖关系
// Define all the dependencies here
ProdSearchServ : "ProdSearchService",  

这样做:

.when("/products/search/:page", {
        templateUrl: "products.html",
        controller: "ProductsSearchController",
        resolve: {
            resultData : function(ProdSearchService) { //as you defined it before
                return ProdSearchService.searchProducts();
            }
        }
    })

有一个类似的问题here