在angularJS中使用工厂方法时,Undefined不是函数错误

Undefined is not a function error when using factory method in angularJS

本文关键字:Undefined 错误 函数 方法 angularJS 工厂      更新时间:2023-09-26

我在代码中找到TypeError: undefined is not a function的解决方案时遇到了问题。我有以下app.js:

var app =  angular.module('test', ['ngRoute', 'test.services', 'test.directives', 'test.controllers']);
app.config(function ($routeProvider, $httpProvider, $locationProvider) {
  $locationProvider.html5Mode(true);
  $routeProvider.
    when('/q/:q', {
      templateUrl: '/templates/productlist.html',
      controller: 'ProductCtrl'
    }).
    otherwise({
      redirectTo: '/q'
    });
});

然后是控制器

var controllers = angular.module('test.controllers', []);
controllers.controller('ProductCtrl', ['$scope', '$routeParams', 'ProductFactory',
  function ($scope, ProductFactory, $routeParams) {
    $scope.query = $routeParams.q;
    $scope.products = ProductFactory.query({query: $scope.query});
  }]);

和一个工厂

var services = angular.module('test.services', ['ngResource']);
var baseUrl = 'http://localhost'':8080';
services.factory('ProductFactory', function ($resource) {
    return $resource(baseUrl + '/test/smart/:query', {}, {
        query: { method: 'GET', isArray: true }
    })
});

这段代码导致在我的控制器$scope.products = ProductFactory.query({query: $scope.query});行上的上述TypeError加载。此外,在调试我的代码时,我看到$routeParams.q为空或未定义。我想要的是,在我的控制器中,$scope.products变量成为查询结果的数组。

我做错了什么?

请尝试使用正确的函数参数,

controllers.controller('ProductCtrl', ['$scope', '$routeParams', 'ProductFactory',
  function ($scope /*ProductFactory*/, $routeParams, ProductFactory) {
    $scope.query = $routeParams.q;
    $scope.products = ProductFactory.query({query: $scope.query});
  }]);