N
N
Nikita Petrov2017-02-22 14:04:46
Angular
Nikita Petrov, 2017-02-22 14:04:46

How to properly manage data in angular 1.x?

Hello!
I am tormented by such a question: How to properly manage data in angularJS 1.x ?
The trick I'm using now:

angular.module('app')
  .service( 'UserService', UserService )
  .controller('UserController', UserController);

function UserService() {
  this.user = {
    settings: {
      name: 'nikler'
    }
  }
}

function UserController(UserService) {
  this.user = UserService.user;
}

We change for example user.settings.namein the service, the changes will be displayed in the controller and vice versa.
I saw somewhere the same implementations with getters and setters in the service. But then it is not clear how to set up a synchronization mechanism so that changes that have occurred in one entity are immediately displayed on another.
Can you please tell me what are the ways to organize data management in angular 1.x?
I also saw a mention of a bunch of angular + redux somewhere . Who used it, tell me how convenient it is, does it increase the complexity? (I'm new to redux).
Maybe I googled badly, but Google was not very helpful. Thank you in advance.

Answer the question

In order to leave comments, you need to log in

3 answer(s)
R
Roman, 2017-02-24
@webnikler

It's good when the areas of responsibility are distributed:
The controller is responsible for displaying data and user input.
And the service is responsible for updating and storing data.
In this approach, it is very easy to implement patterns such as undoing user changes and reverting to a previous version. Since it is always stored in the service.
Or, for example, to warn the user that there is unsaved data - before leaving the form, since you can compare the model from the controller with the version of the model in the service.
For good - there should be one data change point -> Service, and the controller should work with their copy

A
Aleksei Podgaev, 2017-02-24
@alexiusp

Can be done in different ways. The main thing from the very beginning is to decide who will make changes to the data. I would recommend that changes be made only in one place (for example, in the controller indicated in the example). If all and sundry change your data - other services, directives, other nested controllers, then you will very soon lose control over what is happening in your application and where the changes come from. The approach with a single person responsible for changing the data greatly simplifies life in applications with a complex architecture, although it sometimes requires unnecessary scrolling of event handlers up the component hierarchy.

E
emp1re, 2017-02-22
@emp1re

The object changes because it is the same. Controller or service has nothing to do with it.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question