2017-10-06 66 views
0

一個Injectable類的'this'引用注入組件的this。如何引用助手方法方法使用來自Injectable的'this'?

希望使用注入從組件抽象代碼。但是,當我使用'this'引用@Injectable類中的父方法中的其他方法,然後嘗試使用它注入的組件時。

該方法稱爲this.enclosedMethod不起作用。錯誤:this.enclosedMethod不是一個函數。記錄「this」表明它引用了已注入的Component類。例如

@Injectable() 
export class UploaderService { 

constuctor() {} 

    parentMethod() { 
     this.logSomething(); 
     const that = this; 
     that.logSomething(); 
    } 

    logSomething() { 
     console.log('Testing'); 
    } 

} 


@Component() 
export class AppComponent implements OnInit { 

    constructor(private upload: UploaderService) { 
     this.parentMethod = upload.parentMethod; 
    } 

    NgOnInit(): void { 
     this.parentMethod(); // this.logSomething is not a function or that.logSomething is not a function 
    } 

} 

問:你怎麼用其他方法方法在注射?我此刻一片空白

回答

0

how do you use methods in other methods in an Injectable? I am drawing a blank at the moment

修復

解決您的this

@Component() 
export class AppComponent implements OnInit { 

    constructor(private upload: UploaderService) { 
     this.parentMethod =() => upload.parentMethod(); // FIXED! 
    } 

    NgOnInit(): void { 
     this.parentMethod(); 
    } 

} 

更多

+0

太好了,謝謝;) – jamie

相關問題