我有一个相当简单的 Angular 应用程序,它在我的开发机上运行正常,但在部署后却出现了这样的错误信息(在浏览器控制台中):
Uncaught Error:[$injector:unpr] http://errors.angularjs.org/undefined/$injector/unpr?p0=tProvider%20%3C-%20t%20%3C-%20%24http%20%3C-%20%24compile`.
除此之外没有其他信息。页面首次加载时会出现这种情况。
我正在运行 ASP.NET MVC5、Angular 1.2RC3,并通过 git 推送到 Azure。
谷歌搜索没有发现任何有趣的东西。
有什么建议吗?
编辑:
我使用的是 TypeScript,并使用 $inject
变量定义了我的依赖关系,例如:
export class DashboardCtrl {
public static $inject = [
'$scope',
'$location',
'dashboardStorage'
];
constructor(
private $scope: IDashboardScope,
private $location: ng.ILocationService,
private storage: IDashboardStorage) {
}
}
我相信这应该(或者说是为了)解决在最小化过程中出现的本地变量重命名问题,而该问题可能会导致此错误。
不过,这显然与最小化过程有关,因为当我在开发机器上设置 BundleTable.EnableOptimizations = true
时,就能重现这一错误。
如果你按照你的链接进行操作,就会发现该错误是由于 $injector 无法解析你的依赖关系造成的。这是 angular 的一个常见问题,因为在生产过程中,javascript 会被缩减/优化/不管你做了什么。
问题出在例如控制器上;
angular.module("MyApp").controller("MyCtrl", function($scope, $q) {
// your code
})
最小化会将 $scope
和 $q
变为随机变量,而不会告诉 angular 要注入什么。解决方法是像这样声明依赖关系:
angular.module("MyApp")
.controller("MyCtrl", ["$scope", "$q", function($scope, $q) {
// your code
}])
这样应该就能解决问题了。
再重申一遍,我所说的一切都在错误信息提供给您的链接中。
如果您为 angular app\resources\directives 和其他内容设置了单独的文件,那么您可以像这样禁用 angular 应用程序捆绑包的最小化(在捆绑包配置文件中使用 new Bundle() 而不是 ScriptBundle()):
bundles.Add(
new Bundle("~/bundles/angular/SomeBundleName").Include(
"~/Content/js/angular/Pages/Web/MainPage/angularApi.js",
"~/Content/js/angular/Pages/Web/MainPage/angularApp.js",
"~/Content/js/angular/Pages/Web/MainPage/angularCtrl.js"));
这样,Angular 应用程序就会未经修改地出现在 bundle 中。