Angular services: best pratice for observables -




i'm in process of moving basics of angular learning more best practices. i've started trying adopt more reactive approach lately, there 1 thing can't find answer googling.

now, can have following simple method in service:

   public getsomething(): observable<something>    {       return this._http.get("api path")    } 

so, in calling component, obviously, can subscribe , notified when changes streamed. if there several parts of application should notified change?

so, alternative, like:

   private _somethingsubject: subject<something> = new subject<something>();    public something$: observable<something> = this._somethingsubject.asobservable();      public getsomething()    {       return this._http.get("api path")          .subscribe((something) => { this._somethingsubject.next(something) })  } 

now, consumer of service can listen changes something$. of course, need know there connection between "detached" stream , method called.

if seems tutorials go first approach, reactive programming? best solution? }

you second approach valid use case describing. in experience, tutorials either covering basics (i.e. first approach), or take 1 step further second approach by implementing state management library such ngrx.

ngrx - state management

using state management library (ngrx best pick, since it's backed google folks) could considered best practice when building reactive applications.

in essence, benefit you're getting centralized store of data every component or service in application can subscribe too. kind of scenario you're creating subject in service - bigger scope 1 service.

why consider ngrx on shared services?

redux - ngrx is, angular implementation of redux pattern. redux pattern, extremely shortly summarized is:

  • a centralized store state lives
  • a centralized place (your reducers) responsible changing state
    • your state immutable
    • your reducer functions can triggered dispatching called actions

so why these points good? well, when have strict , standardized way of managing state in application, debugging becomes way easier, since know state have been modified in 1 single place.

making application reactive easier, of implementation has access same store (you can split store, that's topic).

here tutorials on subject:





wiki

Comments

Popular posts from this blog

elasticsearch - what is the equivalent data type for geo_point in hibernate search? -

Jenkins: find build number for git commit -

firebase - How to wait value in Ionic 2 -