1

我一直在尝试使用 Angularjs 和 Typescript 将工厂注入控制器,但我收到了这个错误Error: [$injector:unpr] http://errors.angularjs.org/1.2.9/$injector/unpr?p0=AuthenticationProvider%20%3C-%20Authentication

我一直在研究,但找不到解决方案,因为我所做的与某些解决方案相似。

这是我的登录控制器模块

import Authentication = require('AuthenticationService');
module LoginController{

export interface UIMainScope extends ng.IScope {
    login: (credential: any) => void;
}

export class Controller {
    static $inject = ['$scope', '$http', 'Main', 'Authentication'];
    constructor (){}
}
export = LoginController
angular.module('App').controller('Controller', LoginController.Controller);

我是不是忘了在这里注入一些东西来调用该方法?

4

2 回答 2

1

这里的问题与这样一个事实有关,即角度$inject不能从 Typescript 中获利require。这些是独立的特征,它们代表不同的概念。

angular's[$inject][1]作为内置的Dependency Injection,只能注入已经注册的内容。它无法访问 Typescript 对象 - 只能访问它自己的(角度的)对象工厂。

正如错误所说:unknown provider 'AuthenticationProvider',我们必须调用:

angular.module('App')
  .factory('Authentication', [... its dependencies ...
      , (params) => new Authentication(params)]);

现在,我们已经在 Angular 中准备好了身份验证,我们可以在控制器内部请求它

语法可能如下所示:

// module with Scope and Controller
module LoginController
{
  export interface UIMainScope extends ng.IScope 
  {
    login: (credential: any) => void;
  }

  export class Controller
  {
    // constructor, instantiating private members this.$scope ...
    constructor($scope: UIMainScope
       , $http :ng.IHttpService
       , Main: any
       , Authentication: any)
    ...
  }
}

// and finally pass it into angular as .controller()
angular.module('App')
  .controller('Controller', [
     '$scope', '$http', 'Main', 'Authentication',
     ($scope, $http, Main, Authentication)  =>
     {
        return new LoginController.Controller($scope, $http, Main, Authentication);
     }
]);

最后:在某些情况下,该Authentication提供商不会从使用 Angular 启动的蜜蜂中获利,我们也可以使用它。我们根本不需要注册它。只需调用 require,并访问它的方法......但我们必须跳过 angular¨s$inject过程......

这可能不是这种情况,但想象一些QueryStringBuilder......它可能只消耗方法中传递的参数Builder.build(...)

于 2014-07-03T16:26:36.137 回答
0

好像您没有Authentication专门用 Angular 注册的服务:

angular.module('App').controller('Controller', LoginController.Controller)
    // fix based on your code 
    .service('Authentication',Authentication.AuthenticationService); 

该视频可能会有所帮助:https ://www.youtube.com/watch?v=Yis8m3BdnEM&hd=1

于 2014-07-03T23:30:07.720 回答