2016-10-04 25 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