Search code examples
angularjsangularjs-serviceangularjs-http

I am trying to return a data from custom angular JS service to the controller but it is always returning "{}"


I have written a custom angular service that returns the session id after making a post-call to the WCF service. I can see on the chrome's network tab that the call has returned the session-id but when I try to return it through $http.post to the caller it returns "{}" object.

I've followed all the questions/answers related to this problem in stackoverflow, etc. but to no avail. I know there is a problem with the handling of promise that was returned by the post-call but I don't know and not able to pin-point what's wrong and where.

This is the custom service.

angApp.service('RPCService', function($http) {

    var url_login = 'http://xxxxxxx';

    this.Login = function(request) {

        return $http.post(url_login, request)
                            .then(function (result) {
                                return result.data;
                                },
                            function (data, status) {
                                console.log(data + status);
                            });

    };

This is the caller.

angApp.controller('exportController', ['$scope', 'RPCService', function ($scope, RPCService) {

    $scope.export = {};

    $scope.exportLogin = function(){

        var req = {
                    "SiteId" : $scope.export.xxx,
                    "UserName" : $scope.export.xxx,
                    "Password" : $scope.export.xxx
                    };

        $scope.export.sessionId = RPCService.Login(req);
    };

I expected the output as "SessionId" : "xxxxxxxx" but I am getting "{}"


Solution

  • $http.post returns a promise and that is what your service method is returning

    Change

    $scope.export.sessionId = RPCService.Login(req);
    

    To

    RPCService.Login(req).then(function(data){
       $scope.export.sessionId = data;
    })