Search code examples
angularserviceprivatepublic

Angular public service


I want to use a value coming from a service into my HTML.

import { Injectable } from '@angular/core';
@Injectable()
export class DataService {
  foo =  'Foo';
}

Most examples I found use private service

import { Component } from '@angular/core';
import { DataService } from './data.service';

@Component({
  selector: 'my-app',
  template: '{{foo}}',
})

export class AppComponent {
  get foo() { return this.dataService.foo; }
  constructor(private dataService: DataService) {}
}

I am wondering why not declare the service as Public to avoid the getter

import { Component } from '@angular/core';
import { DataService } from './data.service';

@Component({
  selector: 'my-app',
  template: '{{dataService.foo}}',
})

export class AppComponent {
  constructor(public dataService: DataService) {}
}

Solution

  • This is a basic encapsulation problem https://en.wikipedia.org/wiki/Encapsulation_(computer_programming). Best practice is to set services as private because each module has a role :

    • Service provide utils functions
    • Component use the service to perform operations

    You can also check this topic for more information : Typescript dependency injection public vs private