【问题标题】:Injecting angular1 service in angular2 directive在 angular2 指令中注入 angular1 服务
【发布时间】:2016-03-15 17:05:30
【问题描述】:

我正在阅读很多关于此问题的文章,例如 thisand thisalso this,但这些文章中的每一篇都是从 NG1 服务是 class 并且可以导出的情况开始的。

我的情况非常不同,我经常在同一个文件中有多个服务,并且它们以非常古老的方式定义,例如

angular.module('App.services').factory('SessionService',
    function() {
        var defer = $q.defer();
        [...]
    }
);

没有class,没有export

而且这个东西在页面中直接用老式的<script src="...">链接了

同时,我正在尝试在 Angular2 中创建新指令,而这些指令需要那些老式的服务。

我知道我应该能够写出这样的东西

import {Injector,Component, Directive, ElementRef, Input, View} from 'angular2/core';

var injector = Injector.resolveAndCreate([
    SessionService
]);

var SessionService = injector.get(SessionService);


@Component({
    selector: 'nav-bar'
})

@View({
    templateUrl: '/app/components/navbar/navBar.html'
})

export class navBar {
    constructor() {

    }
}

当然SessionService 对象是找不到的。

我怎样才能摆脱这个烂摊子?

[附加信息]

使用babel 作为转译器

angular2-annotations 插件添加

了解angular2中Annotations和Decorators区别的好文章:http://blog.thoughtram.io/angular/2015/05/03/the-difference-between-annotations-and-decorators.html

【问题讨论】:

  • 不要尝试导入脚本并手动注入,而是尝试将所有脚本按顺序包含在您的 index.html 中。然后你可以直接通过它的名字在你的控制器中导入一个服务......

标签: javascript angularjs dependency-injection angular babeljs


【解决方案1】:

您只需要利用@Inject

@Component({
  selector: 'nav-bar'
  templateUrl: '/app/components/navbar/navBar.html'
})
export class navBar {
  constructor(private @Inject('SessionService') sessionService) {

  }
}

查看此 plunkr 了解更多详情:http://plnkr.co/edit/U6ygjUUQ04mTGAAaC1pZ?p=preview

您会注意到,对于工厂,您不能使用类。只有服务才有可能……

如果你只使用 ES6,你可以试试这个:

@Component({
  selector: 'nav-bar'
  templateUrl: '/app/components/navbar/navBar.html'
})
export class navBar {
  constructor(sessionService) {

  }

  static get parameters() {
    return [[ new Inject('...'), new Inject('...') ]];
  }
}

【讨论】:

  • 我试图使用@inject 但我得到了Unexpected token。是的,我从 angular/core 导入了 Inject。以及像 @Component 这样的其他符号可以正常工作,没有错误...(使用 babel)
  • 您是否使用UpgradeAdapter 类的bootstrap 方法引导您的应用程序?见我的笨蛋。否则相应的提供者将不存在...
  • 当然可以。我可以告诉你@Inject 对于我的转译器只有在它是一行中的第一条语句时才有效......不知道为什么,但基本上我不能在构造函数中使用它或将它分配给变量......
  • 哦,看来您使用的是 ES6 而不是 TypeScript。我认为你的问题的 réagir。装饰器不在构造函数参数级别。您可以尝试为参数属性创建静态获取: static get parameters() { return [[ Inject('...'), Inject('...') ]]; }
  • 谢谢,我实际上并没有意识到我只使用了 ES6 而不是 TS,最后你的解决方案确实有效,你只需要通过在每个之前添加 new 关键字来修复它Inject.
猜你喜欢
  • 1970-01-01
  • 2016-05-09
  • 2014-02-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-02-08
  • 2016-02-12
  • 1970-01-01
相关资源
最近更新 更多