I have a service which is loading basic system information which I want to share between several components.
If I make a getter method this
in the getter becomes the component's this
if I not use double arrows in the service.
service
import { Injectable } from '@angular/core';
@Injectable()
export class WhoAmIService {
constructor() { }
whoAmI = 'I\'m a service'
getterOne(): string {
return this.whoAmI
}
getterTwo = (): string => {
return this.whoAmI
}
}
component
import { Component } from '@angular/core';
import { WhoAmIService } from './who-am-i.service';
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: [ './app.component.css' ]
})
export class AppComponent {
name = 'Angular';
whoAmI = 'I\'m a component'
getterOne: Function
getterTwo: Function
constructor(
private whoAmIService: WhoAmIService
) {
this.getterOne = whoAmIService.getterOne
this.getterTwo = whoAmIService.getterTwo
console.log('cool', whoAmIService.getterOne())
console.log('cool', whoAmIService.getterTwo())
console.log('why is this different', this.getterOne())
console.log('cool', this.getterTwo())
}
}
https://stackblitz.com/edit/angular-xxsven
Question
Why do I need the arrow function if I assign the getter function to the component?