【问题标题】:Unable to inject my service in Angular resolve inside router configuration无法在路由器配置内的 Angular 解析中注入我的服务
【发布时间】:2017-09-05 19:45:32
【问题描述】:

(我的 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

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

我正在复制下面的 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);

}());

【问题讨论】:

    标签: angularjs angular-routing angular-services


    【解决方案1】:

    这是由您奇怪的命名约定引起的。有时是ProdSearchServ,有时是ProdSearchService

    如果您只是选择一个并始终如一地使用它,那么您就不会遇到这些类型的错误。

    Fixed Plunker

     

    特别是您使用名称ProdSearchService 创建服务,然后尝试使用不同的名称:

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

    我想您认为此代码会为您解决问题。但是,这只适用于传递到控制器的依赖项,而不是一般的函数。对于已经存在的服务,不需要像这样专门定义;而是简单地在控制器中使用正确的名称。

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

    【讨论】:

      【解决方案2】:

      我觉得你说的时候不需要定义依赖

      // 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

      【讨论】:

      • 谢谢!我希望我可以选择两个答案作为接受的答案!
      • @Jamboree 没关系。当你earn 足够reputation 你可以upvote 所有你认为对你有用的答案;)
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-07-11
      • 2021-11-23
      • 1970-01-01
      • 1970-01-01
      • 2022-06-22
      • 1970-01-01
      • 2019-09-19
      相关资源
      最近更新 更多