-1

I created a factory that returns an $http promise.

loginRsrc.factory('loginSrvc', ['$http', function($http){

    var http = $http({
        method: 'POST',
        url: "http://myproj.herokuapp.com/api/signIn",
        data: $.param({email: "joe@gmail.com", password: "1234567"}),
        headers: {'Content-Type': 'application/x-www-form-urlencoded'}
    });

    return http;

I use this factory in a controller. But I'm getting funny behaviour.

When I say

loginSrvc()
        .success(function(res){
            console.log("res:");
            console.log(res);
        })
        .error(function(res){
            console.log("res");
            console.log(res);
        });

I get an error that TypeError: object is not a function.

But when I say (omitting parentheses)

loginSrvc
        .success(function(res){
            console.log("res:");
            console.log(res);
        })
        .error(function(res){
            console.log("res");
            console.log(res);
        });

it works great! The success prints to the console.

I can't understand this weird behaviour. Just adding a success function calls the $http activity?

This is my full controller:

loginApp.controller('loginCtrl', ['$scope', '$state', 'loginSrvc', function($scope, $state, loginSrvc){

    $scope.loginForm = {};
    $scope.loginForm.email = "";
    $scope.loginForm.password = "";

    $scope.submit = function(){

        loginSrvc
        .success(function(res){
            console.log("res:");
            console.log(res);
        })
        .error(function(res){
            console.log("res");
            console.log(res);
        }); 
    }
}])
CodyBugstein
  • 21,984
  • 61
  • 207
  • 363

2 Answers2

3

Because your service is returning the invoked $http service already, so there's no need to invoke it a second time from the controller. The promise is already available.

A better pattern is to use ngResource such that you can abstract your handlers with their own respective promises for each API end point.

AlienWebguy
  • 76,997
  • 17
  • 122
  • 145
1

That is passing without parentheses is because loginSrvc is an object NOT a function.

Factory API instantiates an Object

Since, you were trying to invoke an Object as a function, that is why you had an error:

TypeError: object is not a function

harshes53
  • 419
  • 1
  • 6
  • 17