1

I need to call a Factory method from a Controller method in Angular. But when I call the Factory method AuthFactory.login(username,password).then(), it shows Error like this

TypeError: AuthFactory.login(...).then is not a function

Plunker code here .

I think I am missing here a concept of AngularJS promises.

1
  • exactly, you are missing a promise which should be returned for you to be able to use the .then - if you can post the factory, we may be able to help you put that in (it's pretty easy, but the docs are terrible) Commented Oct 29, 2015 at 4:48

3 Answers 3

3

For login method, you are sending simple javascript object not promise object.

function login(username, password) {
    var userInfo = {
      "authToken": "6a65dd0c-b35a-429b-a9c0-f5c327ec5d6f",
      "id": "1445138519"
    };
    return userInfo; // Returning javascript object
}

In plunkr, you have some commented code as below:

 // $http.post(API_URL + '/auth/login', {
 //   email: username,
 //   password: password
 // })

So instead returning userInfo, return $http.post object and then use then method.

Sign up to request clarification or add additional context in comments.

Comments

3

You need to wrap the response in a promise, which then resolves.

.factory('AuthFactory', function AuthFactory($http, API_URL, $q) {
 'use strict';
 return {
   login: login
 };

 function login(username, password) {
  var deferred = $q.defer();
  deferred.resolve( 
  {
    "authToken":"6a65dd0c-b35a-429b-a9c0-f5c327ec5d6f",
    "id": "1445138519"
  });
  return deferred.promise;

You return the promise, but resolve the actual result. If you want it to fail, you can do a deferred.reject() which returns the error condition in your then.

Plunker

1 Comment

Thanks @Incognos for making clear about promises . I am happy that it really worked. :)
1

Your are returning an object, not a promise.

If you want to return a promise that resolves to that object is pretty simple:

return $q.when(userInfo);

http://plnkr.co/edit/YeE8JmqcDSKqQY969Kpo?p=preview

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.