0

可注入类的“this”引用了注入组件的 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 
    }

}

问题:您如何在 Injectable 的其他方法中使用方法?我现在正在画一个空白

4

1 回答 1

0

您如何在 Injectable 的其他方法中使用方法?我现在正在画一个空白

使固定

修复你的this

@Component()
export class AppComponent implements OnInit {

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

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

}

更多的

于 2017-10-06T05:23:18.303 回答