Angularjs:使用$ http的Singleton服务

时间:2014-04-22 12:00:56

标签: javascript angularjs angularjs-service

是否可以使用$ http创建服务,这将从控制器调用时将方法,url,成功和失败回调作为参数。

我想使用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);
                    }
                });
            }

我正在为app和内部服务使用https://github.com/StarterSquad/startersquad.github.com/tree/master/examples/angularjs-requirejs-2文件夹结构,我有以下代码

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}

                });
    }]);
});

并且在控制器中我有以下代码

  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())
}]);
});

返回[$ promise:Object,$ resolved:false]如何从中获取数据?

2 个答案:

答案 0 :(得分:2)

AngularJS中的服务始终是单身,因此您无需做任何事情即可实现。但是,您似乎并不想要单个因素,因为您希望传递不同的值。因此,您可能希望添加自己的服务工厂功能。类似的东西:

function MyHTTPService($rootScope, url, method) {
  this.$rootScope = $rootScope;
  this.url = URL;
  this.method = method;
}
MyHTTPService.prototype.serverCall = function () {
  // do server call, using $http and your URL and Method
};

App.factory('MyHTTPService', function ($injector) {
  return function(url, method) { 
    return $injector.instantiate(MyHTTPService,{ url: url, method: method });
  };
}); 

可以使用

调用
new MyHTTPService("http://my.url.com", "GET");

答案 1 :(得分:1)

您也可以将$ resource用于此类用途。

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'}
    });
}]);

使用示例:

    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);
            });

    }