Search code examples
javascriptangularjsangularjs-service

Angularjs: Singleton service using $http


is it possible in angular to create service using $http which will take method, url, success and failure callback as parameters when called from controller.

I want to achieve following kind of functionality using angular.

  var ajax = {
            URL: "webservice url",
            loggedIn: false,
            importedId: "",
            token: '',
            userdetails: new Backbone.Collection.extend({}),
            serverCall: function(method, data, successCallBack, failureCallBack) {
                var that = this;
                //console.log(method);
                //console.log(successCallBack);
                that.showLoading();
                $.ajax({
                    url: that.URL + method,
                    method: 'post',
                    data: data,
                   // contentType:"application/json; charset=utf-8",
                    success: function(data) {
                        that.hideLoading();
                        if (that.checkForError(data))
                        {
                            successCallBack(data);
                        }

                    },
                    fail: function(data) {
                        that.hideLoading();
                        failureCallBack(data);
                    }
                });
            }

i am using https://github.com/StarterSquad/startersquad.github.com/tree/master/examples/angularjs-requirejs-2 folder structure for app and inside services i have following code

define(['./module'], function(services) {
'use strict';
services.factory('user_resources', ['$resource', '$location', function($resource, $location) {

        return $resource("", {},
                {
                    'getAll': {method: "GET", url:'JSON/myList.JSON',isArray:true}

                });
    }]);
});

and in controller i have following code

  define(['./module'],    function (controllers) {
'use strict';
controllers.controller('myListCtrl',['Phone','Phone1','loginForm','$scope','$http','user_resources','CreditCard',function(Phone,Phone1,loginForm,$scope,$http,user_resources,CreditCard){
    console.log(user_resources.getAll())
}]);
});

which returns [$promise: Object, $resolved: false] how to get data from that?


Solution

  • you could also use $resource for this type of usage.

    angular.module('MyApp.services').
    factory('User_Resource',["$resource","$location", function ($resource,$location){
        var baseUrl = $location.protocol()  + "://" + $location.host() + ($location.port() && ":" + $location.port())  + "/";
        return  $resource(baseUrl+'rest/users/beforebar/:id',{}, {
            query: { method: 'GET', isArray: true },
            get:   { method: 'GET' },
            login: { method: 'POST', url:baseUrl+'rest/users/login'},
            loginAnonymous: { method: 'POST', url:baseUrl+'rest/users/loginAnonymous'},
            logout: { method: 'POST', url:baseUrl+'rest/users/logout/:id'},
            register: { method: 'POST', url:baseUrl+'rest/users/register'}
        });
    }]);
    

    Example of usage :

        userSrv.logout = function(user,successFunction,errorFunction)
        {
            var userSrv = new User_Resource();
            userSrv.$logout({user.id}, //params
                function (data) {   //success
                    console.log("User.logout - received");
                    console.log(data);
                    if (successFunction !=undefined)
                        successFunction(data);
                },
                function (data) {   //failure
                    //error handling goes here
                    console.log("User.logout - error received");
                    console.log(data);
                    var errorMessage = "Connexion error";
                    if (errorFunction !=undefined)
                        errorFunction(errorMessage);
                });
    
        }