2016-10-04 56 views
0

注:我使用安古拉RC2如何访问Angular 2中的服务指令?

我的目标是:设置属性值的指令从服务

我成立了它使用的服务的自定义指令:

@Directive({ 
    selector: '[chooseFile]' 
}) 

@Injectable() 
export class ChooseFileDirective implements OnInit { 
    property1: number = 1; 

    constructor(private _element: ElementRef, private _uploadService: UploadFile) { } 

    ngOnInit() { 
    this._uploadService.foo(); 
    }  
} 

UploadService

@Injectable() 
export class UploadFile { 

    constructor(private _chooseFileDirective: ChooseFileDirective) {} 

    foo() { 
    // update variable on calling directive 
    _chooseFileDirective.property1++; 
    } 
} 

错误我收到:

Error: (SystemJS) Error: Can't resolve all parameters for UploadFile: (?)

我试过(单和一起)什么:

  • 添加@Injectable()装饰的指令
  • 在指令添加到提供商app.component
  • add in service's constructor:@Inject(ChooseFileDirective)_chooseFileDirective:ChooseFileDirective

回答

1

Angular 2不允许注入指令/组件。这将是一种指导聆听服务的方式。 您可以创建一个代表fileUploaded $事件的EventEmitter,因此在指令中您可以这样做:

export class ChooseFileDirective implements OnInit { 
    property1: number = 1; 

    constructor(private _element: ElementRef, private _uploadService: UploadFile) { } 

    ngOnInit() { 
    this._uploadService.foo(); 
    this.fileUploaded$.subscribe(file => //do your stuff) 
    }  
} 
+0

谢谢。看起来很不错我需要重构应用中的其他一些东西,然后我也会测试这个并接受答案:) – dragonmnl