S
S
Sergey2016-10-07 13:41:29
JavaScript
Sergey, 2016-10-07 13:41:29

Give advice on how best to work with rest api on angular2 at the moment?

Interested in a set of best practices or ready-made components for working with REST on angular2 . (something like restangular... but ( https://github.com/mgonto/restangular/issues/1318)) (((
Thanks in advance.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
_
_ _, 2016-10-07
@karmis

I can only speak for myself - $resource and Restangular only make it harder to manage state in a large application. Switched to Redux for state management. There is a Transport service with settings that implements basic operations, used in Redux actions.
Approximately like this:

@Injectable()
class Transport { 
  constructor(private _http: Http, private _config: TransportConfig) {
  }
  // Тут get, post, put, delete с использованием _config (apiEndpoint и.т.д)
}

class SessionActions {
  constructor(private _s: Store, private _t: Transport) {
  }

  loadSession() {
    this._s.dispatch(actionLoad());
    this._t.get('/session')
      .then(actionLoadCompleted)
      .catch(actionLoadError);
  }
}

@NgModule({
  id: 'store',
  providers: [
    Store,
    {
      provide: SessionActions,
      useFactory: (store, transport) => new SessionActions(store, transport),
      deps: [Store, Transport]   
    }  
  ]
})

Well, in any component
constructor(private _s: Store, private _actions: SessionActions) {
  _s.subscribe('session.user', (user) => {
    this.user = user;
  });
  _actions.loadSession();
}

A big plus is that the state management code can be reused with any JS framework, it is not tied to Angular2

R
Ruslan Lopatin, 2016-10-07
@lorus

To just work with Http REST service is enough.
But if you want to show request statuses, errors, prevent form resubmissions, etc., then you get more routine code (boilerplate) than the actual request processing logic.
I solved this problem for myself by writing a library: ng2-rike
Now I use it on my projects. Makes life much easier.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question