Search code examples
angularjsangularjs-serviceangularjs-controller

where should i use the $http in angularjs? -> difference between factory and service


wher should i use the $http in angularjs? in the controller or in the service? i have already implement it in the service, but i want to execute not at the start of the app, i want to execute after some user actions, is this possible in the service?

'use strict';

/* Services */

// Demonstrate how to register services
// In this case it is a simple value service.
angular
    .module('myApp.services')
    .service(
            'RestService',
            function($http, $log) {

                this.getERPProfile = function() {
                    var request = request;
                    request = JSON.stringify(request);


                    $http(
                            {
                                url : url,
                                method : "POST",
                                headers : {
                                    'Accept' : 'text/xml',
                                    'Content-Type' : '"text/xml; charset=\"utf-8\""'
                                },
                                dataType : 'xml',
                                data : request

                            }).success(
                            function(data, status, headers, config) {
                                var v1 = data;
                                return data;
                                $log.log(v1);
                            }).error(
                            function(data, status, headers, config) {
                                var v2 = status;
                                return data;
                                $log.log(v2);
                            });
                };

and has someone a good documentation about the difference of factory and service? the angulajs site does not help me to understand.

thanks for your help!


Solution

  • Services are instantiated, only once, the first time they are called. They're used to share logic and expose data between controllers, for example. Controllers are the glue between the view and the model, like in any MVC framework.

    Running it at the start of the app or not has nothing to do with doing the $http request from a controller or from a service. Mae the http request when you need it.

    Notice that controllers are instantiated when angular finds <div ng-controller=whatever>... . If your http request is there, it'll be triggered. There was a similar question about services and factories a few weeks ago and another one about injecting a service in a controller.