B
B
Bogopodoben2016-11-15 15:28:12
Angular
Bogopodoben, 2016-11-15 15:28:12

How to use the service to work with data in it?

Good day to all. Question such:
How it is correct to yuzat service for work with data in it? (deleting, adding, editing)
At the moment, after receiving a list of accounts from the server, they are stored in the "accountsList" array as a promise, and then I fall into a stupor, how to properly process such data in the service and is it correct?
And how can such a service be brought to an even better, more correct and convenient form?
And I would be glad to see examples of working with services on large projects.

(function(){
  'use strict';
  angular
    .module('app.manager.finance.accounts')
    .factory('AccountsFinanceService', AccountsFinanceService);

  AccountsFinanceService.$inject = ['Http', 'Notification', 'API'];

  function AccountsFinanceService(Http, Notification, API) {
    var AccountsFinanceService = {
      listAccounts  : listAccounts,             // Список счетов
      getAccounts   : getAccounts,              // Получение счетов
      setAccounts   : setAccounts,              // Редактирование счета
      deleteAccounts: deleteAccounts            // Удаление счета
    };
    var accountsList = [];

    function listAccounts() {
      if (accountsList.length === 0) {
        accountsList = AccountsFinanceService.getAccounts();
      };
      return accountsList;
    };

    function getAccounts() {
      var config = {
        url: API.url + 'finances/accounts',
        method: 'GET'
      };
      return Http(config).then(function(res){
        return res.data;
      }, function(res){
        Notification.error('Произошла ошибка, попробуйте позже.');
      });
    };

    function setAccounts() {
      //body
    };

    function deleteAccounts(index, id) {
      var config = {
        url: API.url + 'finances/accounts/' + id,
        method: 'DELETE'
      };
      Http(config).then(function(res){  
        Notification.success('Запись успешно удалена.');
      }, function(res){
        Notification.error('Произошла ошибка, попробуйте позже.');
      });
    };

    return AccountsFinanceService;
  };

})();

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Aleksei Podgaev, 2016-11-24
@alexiusp

I would separate the work with the model and http into different modules. Then, in the module responsible for requests to the server, it would be possible to implement both work with promises and caching as needed, and the module responsible for working with the model would be very easy and understandable. Do you need any post-processing of the incoming data, or is it already in a format convenient for presentation? If the latter, then it is better to work directly with promises - return promises to those components that need the corresponding data.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question