【问题标题】:AngularJs script doesnt work after deployment, It gives error [$injector:unpr]AngularJs 脚本在部署后不起作用,它给出错误 [$injector:unpr]
【发布时间】:2017-03-31 02:40:10
【问题描述】:

我一直在构建一个 Web 项目,有时我会尝试发布并查看所有内容,就像它在 localhost 中所做的一样。这一次,我添加了 angularjs 来获取/显示货币并再次部署项目。但是,它会在浏览器中向用户显示 {{currencies}}。

Error: [$injector:unpr] http://errors.angularjs.org/1.5.8/$injector/unpr?p0=nProvider%20%3C-%20n%20%3C-%20CurrencyController

我的 angularjs 代码看起来像这样...

app.controller("CurrencyController", function ($scope, $http) {
        $http.get('http://dummy.com/api/getcurrencyformainscreen').
                success(function (data, status, headers, config) {
                    $scope.currencies = data;
                }).
                error(function (data, status, headers, config) {
                    //alert(data);
                })

});

我做错了什么?

【问题讨论】:

  • 错误告诉你没有找到 CurrencyController。可能有多种原因。包含控制器的 js 文件是否包含在您的 html 中?仅供参考,使用 .success()/.error() 处理 $http 承诺已被弃用,取而代之的是 .then()
  • 但是,当我在本地运行时它可以找到

标签: c# angularjs asp.net-mvc


【解决方案1】:

如果您在部署项目时 JavaScript 文件被缩小并且 AngularJS 服务没有被正确“注入”,则可能会发生这种情况。如果是这样,请尝试像这样修改您的代码:

var currencyCtrl = function($scope, $http) {
  $http.get('http://dummy.com/api/getcurrencyformainscreen').
  success(function(data, status, headers, config) {
    $scope.currencies = data;
  }).
  error(function(data, status, headers, config) {
    //alert(data);
  })

};
// inject dependencies properly for minification process
currencyCtrl.$inject['$scope', '$http'];

app.controller("CurrencyController", currencyCtrl);

这是因为 AngularJS 依赖于依赖注入。在开发模式下,参数($scope,$http)具有相同的名称,AngularJS 注入依赖项(具有相同名称的服务)没有问题,但在 JavaScript 文件的缩小版本中,参数的名称发生了变化随机,因此您必须使用currencyCtrl.$inject['$scope', '$http']; 代码手动注入它们。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-02-13
    • 1970-01-01
    • 2014-08-01
    • 2016-10-21
    • 2018-11-19
    • 1970-01-01
    • 2023-01-22
    相关资源
    最近更新 更多