What advantages does Angular Service offer when gathering information compared to utilizing only $http?

Comparing Two Approaches:

Approach A.

  1. Creating app module
  2. Using a service to store model data
  3. Implementing a controller to retrieve data from the service

File 1: Users.js:

      angular.module('users', []);

File 2: userService.js:

angular.module('users').service('userService', ['$q', UserService]);

  function UserService($q) {
    var users = [
      {
        name: 'Bob Smith',
        age: 26,
        address: 'London',
      },
      {
        name: 'John Simpson',
        age: 41,
        address: 'New York',
      },
      {
        name: 'Maria West',
        age: 36,
        address: 'Chicago',
      }
    ];

    // Promise-based API
    return {
      loadAllUsers : function() {
        // Simulate async nature of real remote calls
        return $q.when(users);
      }
    };
  }

})();

File 3: UserController.js:

          angular.module('users').controller('UserController', ['$scope', function($scope) {

        $scope.selected     = null;
        $scope.users        = [];
        $scope.selectUser   = selectUser;
        $scope.toggleList   = toggleUsersList;
        $scope.makeContact  = makeContact;

        userService
          .loadAllUsers()
          .then( function( users ) {
            $scope.users    = [].concat(users);
            $scope.selected = users[0];
          });
}]);

Approach B:

  1. Creating app module and controller that fetches model data from a .json file using the $http service.
  2. A .json file to hold the model data.

File 1: Users.js:

      angular.module('users', []);

         .controller('userController', [
            '$scope', 
            '$http', 
            function($scope, $http, $routeParams) {

            $http.get('data.json').success(function(data) {
            $scope.userData = data; 
            });

         }]);

File 2: userService.json

         [
          {
            'name': 'Bob Smith',
            'age': 26,
            'address': 'London',
          },
          {
            'name': 'John Simpson',
            'age': 41,
            'address': 'New York',
          },
          {
            'name': 'Maria West',
            'age': 36,
            'address': 'Chicago',
          }
        ];

While Approach B seems more straightforward, some prefer Approach A for its advantages. Can anyone shed light on this?

Answer №1

Definitely, Approach A seems to be the preferred choice as it adheres to the principles of separation of concern and the Single Responsibility Principle.

Service

  • This component is responsible for fetching data from the back-end.
  • It exposes various methods to other components for retrieving data from a single source.

Controller

  • Acts as a bridge between services and views.
  • Handles view-specific business logic as well.

Why is Approach B not recommended?

Simply placing an ajax call within a controller may seem convenient initially.

However, imagine if you need to display the same userData on multiple pages - what would you do then? You might end up duplicating the code in another controller, leading to code repetition and maintenance issues down the line. This approach lacks Code Maintainability.

On the contrary, opting for Approach A would result in more maintainable and organized code.

Edit

In Approach A, avoid hardcoding all data. Instead, fetch it from the server either through server API calls or by retrieving data from a .json file. Additionally, consider refactoring your service code in Approach A to streamline the process. The updated service code eliminates the need for the $q service as the $http methods already return promises, enabling a cleaner promise chain pattern utilizing .then.

angular.module('users').service('userService', ['$http', UserService]);
  function UserService($http) {
    return {
      loadAllUsers: function() {
        // Simulate async nature of real remote calls
        return $http.get('users.json'); //return promise from here
      }
    };
  }
})();

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Creating animated effects through Javascript and CSS triggered by user events

As a beginner in javascript and CSS, I am experimenting with creating a simple animation that adjusts the transparency of an image when triggered by an event. However, I am facing an issue where the animation only works every other time the function is cal ...

The content of btn-id element in Angular is showing as undefined

I have a JavaScript file located at sample/scripts/sample.js and there are 8 HTML files in the directory sample/src/templates/. My goal is to select a button on one of the HTML files. When I tried using angular.elemnt(btn-id).html(), I received an 'un ...

Displaying Bootstrap star rating twice in a recursive manner

After reading about the issue with Bootstrap star rating displaying twice on Stack Overflow, I found myself facing a similar problem. <div class="row"> <input id="input-id123" type="number" class="" min=0 max=6 data-stars=6 step=1> </di ...

How can Reactjs access a configuration file?

I am struggling to find a solution for reading a properties file in reactJS. I have come across the "properties-reader" module but I can't figure out how to make the require function work. Is there an easier way? For instance, import React, { Com ...

When making Axios GET requests, HTML receives promises that may remain empty

I've spent the entire day trying to figure out why this isn't working. Here's a simplified version of the HTML table using Vue v-for: <table id="timeSheet-datatable" class="table table-striped dt-responsive w-100"> ...

Dirty context detected in Material-UI TextField

Trying to understand how to check for dirtyness with material-ui's FormControl or TextField component. The TextField demo page mentions that TextField is made up of smaller components (FormControl, InputLabel, Input, and FormHelperText) which can be c ...

How come my post isn't being saved to the page after I refresh it?

Utilizing Javascript, NodeJS, MongoDB, Express Within my application, a user is expected to enter text in an input field and upon clicking the submit button, the text should appear on the page. I have succeeded in posting text to the page; however, after ...

Tips for validating updates in MongooseEnsuring data integrity is

My current Schema does not validate upon updating. Can you please point out where I went wrong and help me fix it? ...

I'm encountering an issue with VS Code where it is unable to identify ejs tags within my project

I'm running into an issue with Vs code where it's not recognizing ejs output tags when they're inside an html tag, like in the input tag below : <input type="checkbox" name="checkbox" value="<%=item._id%>" onChange="this.form. ...

What is the best way to find the longest element with the same class name using jQuery?

How can I dynamically find elements with the same length of class names? var className = $('.floor-4').attr('class').split(' ')[1]; var classLength = $('.' + className).length; Here is the HTML code: <div id="d ...

Encountering difficulties with image processing on a web page

Recently, I've been experimenting with uploading an image and converting it to a grayscale version on my webpage. Oddly enough, the javascript code works perfectly when tested locally but fails to generate the grayscale image once integrated onto the ...

"Enhance your AngularJS app with the seamless functionality of

Is there anyone who can assist me with a sample code? I am looking to implement a feature where I can select a country using AngularJS ui-select2, and upon selection, load the corresponding states in a different select2 dropdown. The data for countries an ...

Drop-down menu in a table cell overflowing with lengthy text, causing the table to collapse

I'm facing an issue with my table where I have inputs and selects inside <td>. The problem arises when the text in the options of the <select> element is too long, causing the <td> to expand and disrupt the overall layout of the tabl ...

JavaScript's counter variable can become confusing when used in an if statement

Struggling as a beginner in javascript, I find myself stuck on writing an If statement that triggers after the fourth turn. My goal is to have an alert pop up once the user has clicked on four options. The counter variable "turns" was added to track prog ...

Struggling to input data into Excel using Selenium WebDriver

I encountered an issue while attempting to write two strings to an Excel sheet using the following code. The error message I received was: java.lang.IllegalArgumentException: Sheet index (0) is out of range (no sheets) FileOutputStream fout=new FileOutput ...

The login functionality on Passport.js is not syncing with Angular updates

I'm currently in the process of developing my first full-stack MEAN application, but I've encountered some issues due to following an outdated tutorial with newer npm packages. The particular problem arises when handling the login functionality w ...

After executing webpack, it has been noticed that one of the dist files consistently ends up empty

As someone who is new to webpack, I have successfully used the quick start guide to process a simple JS file from src to dist. Everything was working fine. However, I encountered an issue when trying to process more than one JS file. The original tutorial ...

What are the best practices for optimizing the display of my AngularJS website for GoogleBot and Optimizely?

My website, VoteCircle (www.votecircle.com), is experiencing display issues with Google Bot/Optimizely when utilizing A/B tests. The content that is not included in ng-view is showing up fine, but everything within ng-view remains hidden. The site was dev ...

Searching for MongoDB / Mongoose - Using FindOneById with specific conditions to match the value of an array inside an object nestled within another array

Although the title of this question may be lengthy, I trust you grasp my meaning with an example. This represents my MongoDB structure: { "_id":{ "$oid":"62408e6bec1c0f7a413c093a" }, "visitors":[ { "firstSource":"12 ...

show a function written in JavaScript

I’m currently developing an API and looking to demonstrate a JavaScript code example for invoking this API. While writing a test function in JavaScript, I aim to execute and showcase the code for the JavaScript functions. However, my preference is to ha ...