Consider this code snippet:
MyComponent.ts
export class MyComponent {
constructor(private myService: MyService) {
myService.printServiceField();
}
}
MyService.ts
@Injectable({
providedIn: 'root'
})
export class MyService {
readonly myField= 'N/A';
constructor() {}
printServiceField() {
console.log(this.myField);
}
The issue I'm facing is the following error message:
ERROR TypeError: "this is undefined"
I am curious about why this error occurs. If I make the myField static
(and access it with MyService.myField
), then the error disappears. I already have a solution in place, but I would appreciate an explanation of what causes this behavior.