ZeroCool ZeroCool - 1 year ago 98
AngularJS Question

Angular2 is this the right way to use Observables?

How does the 'subscribe' and 'unsubscribe' work with Observable in Angular2?

My architecture is as following:

  1. CRUD(Repo) service that contains CRUD operations and returns an

  2. In-between service that talks to CRUD. This service is injected into components and contains private BehaviorSubjects. I expose the underlying values as such

    get selectedClient(): Observable<Client> {
    return this._selectedClient.asObservable();

    get clients(): Observable<Client[]> {
    return this._clients.asObservable();

  3. At the component level, I access the data by subscribing to previously mentioned getters as such:

    deleteClient() {
    this.selectedClient.subscribe(actualClient => {
    this.clientStore.deleteClient(actualClient).subscribe(response => {
    if (response) {

    updateClient() {
    this.clientUpdateForm.submitClientForm().subscribe(client => {
    if (client) {
    this.growlService.showInfoMessage("Client updated", client.firstName + " " + client.lastName);

    this.selectedClient.subscribe(client => {
    this.clientForm = this.clientUpdateForm.clientForm;

First I want to ask, is there anything wrong with this design?
Secondly, when do I need to unsubscribe and when not to?

The idea is that the 'selectedClient' is the state object for the application,
however it brings all of this 'subscribe/unsubscribe' in every component, and from my understanding if you don't unsubscribe you will add another subscription to the subscription array, which means any change will now trigger the code under the subscription twice.

Should the app have the concept of 'selectedItem' at all?

Answer Source

Your design looks pretty solid. You might want to consider ngrx/store, they also make use of Observables / BehaviorSubjects, but additionally implement Redux pattern, which improves overall code readability and design.

Usually you don't need to unsubscribe from Observables, e.g. HTTP observables complete by themselves after returning a value (or erroring). Observables need to be unsubscribed from when they don't complete, for example Observable.timer, or if retrieving parameters from routerService.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download