0

An Injectable Class's 'this' is referencing the injected component's this.

Wanted to use injectable to abstract code from the component. But when I use 'this' to reference other methods in a parent method in the @Injectable class and then try to use that component that it is injected.

The method thas is called as this.enclosedMethod does not work. Error: this.enclosedMethod is not a function. Logging the 'this' shows that it referencing the Component class that's been injected. For example

@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 
    }

}

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

jamie
  • 690
  • 7
  • 18

1 Answers1

0

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

Fix

Fix your this :

@Component()
export class AppComponent implements OnInit {

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

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

}

More

basarat
  • 261,912
  • 58
  • 460
  • 511