Angular service: should I expose the actual data or should I wrap it with an observable?

Discussão em 'Angular' iniciado por Moshe Shaham, Abril 26, 2025.

  1. Moshe Shaham

    Moshe Shaham Guest

    In Angular (currently 6), should I have a service that exposes a list of objects, or should I wrap this list with an observable?

    this is how i expose a simple list of objects:

    export class TicketService {

    private _tickets: List<Ticket>;

    constructor() { }

    init() {
    this.backend.getTickets().subscribe(tickets => this._tickets = tickets);
    }

    getTickets() {
    return this._tickets;
    }
    }


    this seems very straightforward, this is also how I did it with angularjs 1.x. the components that display the data point to the same object as the service, so any change in the object done in the service, will automatically show in the view layer.

    is this still an accepted pattern in Angular, or I need to use Observables as described here: https://blog.angular-university.io/...s-observable-data-services-pitfalls-to-avoid/

    will the first method work? what are the advantages of the seconds method?

    Continue reading...

Compartilhe esta Página