[英]Injecting angular1 service in angular2 directive
我閱讀大量的文章對此事喜歡這樣 , 這和同時此這些文章,但每一個從其中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中注釋和裝飾器之間的區別: http ://blog.thoughtram.io/angular/2015/05/03/the-difference-between-annotations-and-decorators.html
您只需要利用@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
您會注意到,使用factory不能使用類。 只有服務才有可能...
如果僅使用ES6,則可以嘗試以下操作:
@Component({
selector: 'nav-bar'
templateUrl: '/app/components/navbar/navBar.html'
})
export class navBar {
constructor(sessionService) {
}
static get parameters() {
return [[ new Inject('...'), new Inject('...') ]];
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.