Maks K
Maks K

Reputation: 3914

How save global visible user in angular 2 application?

After login I get user

  private login() {
    let data = { "UserName": "admin" , "Password": "+" };

    this.apiService.doLogin(data).subscribe(
      (res) => this.userService.set('user', res),
      (err) => console.log(err)
    )
  }

How I can implement this userService? * I want get some user data without new call to back end? ** I know about https://github.com/ngrx/store, maybe someone know better solution?

Upvotes: 1

Views: 816

Answers (2)

Kamil Myśliwiec
Kamil Myśliwiec

Reputation: 9178

If you want to storage your logged user details, you can do this in few ways.

Redux store (ngrx):

You could use ngrx store concept - https://github.com/ngrx/store. When you get your user model from backend, you just have to dispatch an action to load data.

Advantages:

  • You could subscribe your user store in all pieces of application, in each component, so you can properly react on every change,
  • User model in store would be immutable - to change anything, you have to dispatch an action, which invokes pure reducer function, so it is not possible to modify any user data by accident.

Service:

Also, you could store your user model object in service as a private variable.

Disadvantages:

  • In Angular 2, services could be global or module scoped. What does it mean? That if you add your user service into global module providers array and by mistake - also as your feature module provider, angular 2 will create two instances of your service, so one of them - will have empty user. Similar problem you can find there - https://angular.io/docs/ts/latest/guide/ngmodule.html#!#q-why-it-is-bad

Upvotes: 2

micronyks
micronyks

Reputation: 55443

HTML5localSorage can be used but for Angular2, ngrx/store is better. It also provides state management so its recommended to use it.

Upvotes: 0

Related Questions