Search code examples
angulardependency-injectionservice

Getter for Angular service property instead of storing it in component


I have a component, MainComponent, which needs access to a User object stored in MainService.

Instead of storing the User object both in MainComponent and MainService, would it be considered bad practice to set up a getter in MainComponent, which returns the instance from MainService? This way, the User object would only be stored in one place.

export class MainComponent implements OnInit {
   get user() {
      return this.mainService.user;
   }
@Injectable()
export class MainService {
    User!: IUser;

Solution

  • Having dug into the Angular DI docs (https://angular.io/guide/dependency-injection-in-action), I discovered that this is actually the exact approach they used for the HeroCacheService:

    @Component({
      selector: 'app-hero-bio',
      template: `
        <h4>{{hero.name}}</h4>
        <ng-content></ng-content>
        <textarea cols="25" [(ngModel)]="hero.description"></textarea>`,
      providers: [HeroCacheService]
    })
    
    export class HeroBioComponent implements OnInit  {
      @Input() heroId = 0;
    
      constructor(private heroCache: HeroCacheService) { }
    
      ngOnInit() { this.heroCache.fetchCachedHero(this.heroId); }
    
      // This part here answered my question!
      get hero() { return this.heroCache.hero; }
    }