Properly work with data in angular

user348173

I am trying to understand how to properly work with data in Angular 1.

I am using component based approach. Let's consider a simple case. I have side navigation and dashboard. I need to show departments data in these components.

import sidenavHtml from './sidenavigation.html';
import sideNavController from './sidenavigation.controller';

export default SideNavigation;

SideNavigation.$inject = [
];

function Sidenav() {
    return {
        restrict: 'E',
        scope: {},
        template: sidenavHtml,
        controller: sideNavController,
        controllerAs: 'ctrl',
        link: function ($scope, elem, attrs) {

        }
    };
}

export default class SideNavigationController {
    ...

    $onInit() {
        this.getDepartments();
    }

    getDepartments() {
        this.departmentService.getDepartments().then((result) => {
            this.departments= result.data;
        });
    }
}

export default class DashboardController {
    ...

    $onInit() {
        this.getDepartments();  
    }

    getDepartments() {

        this.departmentService.getDepartments().then((result) => {
            this.departments= result.data;              
        });
    }
}

export default Departments;  

function Departments($http) {

    function getDepartments() {
        return $http({url: 'http://localhost:9000/api/departments', method: 'GET'});
    }

     function create(newDepartment) {
        return $http.post('http://localhost:9000/api/departments', newDepartment);
    }

    return {getDepartments, create};
}

In the Dashboard component user can create new department (creating is another component which is called from Dashboard component). When user created new department I need to notify SideNavigation and Dashboard about it. So, in the Dashboard and SideNavigation components I use the following code: this.$rootScope.$on('updateDepartmens', ()=> { this.getDepartments(); });

Well, disadvantages of this aproach are obvious. When my app is render I get two http requests and I use $rootScope. I have decided to rewrite service in the following way:

export default Departments;  

    function Departments($http) {
        this.departments;

        function getDepartments() {
           if(!departments) {
             $http({url: 'http://localhost:9000/api/departments', method: 'GET'})
             .then((response) => {                   
                this.departments = response.data;                    
             })
             .catch((err) => {
                console.log('error');   
             });
           }

           return this.departments; 
        }

         function create(newDepartment) {
            $http.post('http://localhost:9000/api/departments', newDepartment)
            .then((response) => {
               // handle response and add to departments;
               ...
               this.departments.push(response.data);
            );
    }  

        return {getDepartments, create};
    }

How do you think is it good approach or there is another way?

How do you think should I use this approach overall or use my first approach(call service method which make http request) when I don't need sharing data and use second approach(bind to variable) when I need sharing data?

One additional question. Do you use mapping server models to client models or just use objects returned from server ?

AndreaM16

How do you think is it good approach or there is another way?

I think your second approach is correct but, if you want to intercept a certain event, for instance, reload data when it gets fetched, you don't want to auto-execute a particular function bound to that event every time.

I had a similar problem recently, I needed to execute a function only when data was fetched by a factory. I hate using $rootScope for such things. I don't like using it because it makes the application messy and I also noticed side-effects on application's benchmarks. But as you know, using $rootScope events like $broadcast and $on is really a good thing.

I found out a better way to realize such thing. Using Postal.js you can create virtual buses on your application that are shared between the components you want. For instance, you can subscribe to a channel reloadItems with both DataFactory and DataController and you'll emit, only on that channel, that you fetched the items and intercept that message on your controller and execute the function bound to that event. After that, if you wish, you can unsubscribe from that channel and free that bus. You can share a particular bus with n different modules.

I noticed that using this library increases overall speed of my application since I'm not attaching anything to $rootScope.

That's an example of usage

// . . . Cool stuff
//Factory
$scope.$bus.publish({
                  channel : 'reloadItems',
                  topic   : 'reloadItems'
                  data    : items
);

// . . . Cool Stuff also
//Controller
$scope.$bus.subscribe({
  channel  : 'reloadItems',
  topic    : 'reloadItems',
  callback : function () {
    reloadItems();
  }
});

I really suggest you to give it a shot. You can find a interesting article on how to use it with Angular here.

How do you think should I use this approach overall or use my first approach(call service method which make http request) when I don't need sharing data and use second approach(bind to variable) when I need sharing data?

I feel like you should not bind these things to a variable. Just use events to manage that. And, as I said before, your second approach is better and more modular.

Do you use mapping server models to client models or just use objects returned from server ?

Personally, I just use objects returned from the server. I like having a slim front-end and I make the most of parsing of data in the back-end, but, if I somehow need to work with data in the front-end, I never do it in controllers, I do that in Factories or Services.

I hope I have been helpful.

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

From Dev

Angular binding does not work properly

From Dev

why splice not work properly in angular js

From Dev

why row click event not work properly in angular?

From Dev

jQuery .serialize() does not work properly in angular

From Dev

Sorting decimal data does not work properly

From Dev

loess on grouped data in plotly does not work properly

From Dev

Angular 2 @input data not properly binding

From Dev

Why won't this angular date-picker appear and work properly?

From Dev

Angular directive doesn't work properly inside an HTML table

From Dev

Angular directive doesn't work properly inside an HTML table

From Dev

aviary (adobe creative SDK) doesn't work properly with angular 2

From Dev

Angular $watch doesn't work properly with state provider

From Dev

Saving hex data in binary using PHP does not work properly

From Dev

$this->upload->data() doesn't work properly

From Dev

Saving hex data in binary using PHP does not work properly

From Dev

How properly work with big data using Swing - performance tips

From Dev

Descending sort in jquery data table does not work properly

From Dev

How to use select properly with firebase data in Angular UI typeahead

From Dev

Unable to properly bind data from controller to a custom directive template, Angular

From Dev

How to use select properly with firebase data in Angular UI typeahead

From Dev

Unable to properly bind data from controller to a custom directive template, Angular

From Dev

Angular service not properly updating my $scope.data in my controller

From Dev

Angular binding does not work in data- attribute

From Dev

Button does not work properly

From Dev

NoUiSlider does not work properly

From Dev

$project does not work properly

From Dev

htaccess does not work properly

From Dev

How to properly work with Timezone?

From Dev

ModelState does not work properly

Related Related

  1. 1

    Angular binding does not work properly

  2. 2

    why splice not work properly in angular js

  3. 3

    why row click event not work properly in angular?

  4. 4

    jQuery .serialize() does not work properly in angular

  5. 5

    Sorting decimal data does not work properly

  6. 6

    loess on grouped data in plotly does not work properly

  7. 7

    Angular 2 @input data not properly binding

  8. 8

    Why won't this angular date-picker appear and work properly?

  9. 9

    Angular directive doesn't work properly inside an HTML table

  10. 10

    Angular directive doesn't work properly inside an HTML table

  11. 11

    aviary (adobe creative SDK) doesn't work properly with angular 2

  12. 12

    Angular $watch doesn't work properly with state provider

  13. 13

    Saving hex data in binary using PHP does not work properly

  14. 14

    $this->upload->data() doesn't work properly

  15. 15

    Saving hex data in binary using PHP does not work properly

  16. 16

    How properly work with big data using Swing - performance tips

  17. 17

    Descending sort in jquery data table does not work properly

  18. 18

    How to use select properly with firebase data in Angular UI typeahead

  19. 19

    Unable to properly bind data from controller to a custom directive template, Angular

  20. 20

    How to use select properly with firebase data in Angular UI typeahead

  21. 21

    Unable to properly bind data from controller to a custom directive template, Angular

  22. 22

    Angular service not properly updating my $scope.data in my controller

  23. 23

    Angular binding does not work in data- attribute

  24. 24

    Button does not work properly

  25. 25

    NoUiSlider does not work properly

  26. 26

    $project does not work properly

  27. 27

    htaccess does not work properly

  28. 28

    How to properly work with Timezone?

  29. 29

    ModelState does not work properly

HotTag

Archive