javascript - Angularjs .then is not a function - Stack Overflow

I need to call a Factory method from a Controller method in Angular. But when I call the Factory method

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.

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.

Share Improve this question edited Nov 1, 2015 at 6:42 SOAMad 3356 silver badges22 bronze badges asked Oct 29, 2015 at 4:45 anandasubedianandasubedi 5111 gold badge7 silver badges17 bronze badges 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) – Sina Khelil Commented Oct 29, 2015 at 4:48
Add a ment  | 

3 Answers 3

Reset to default 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 mented 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.

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

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

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745361082a4624362.html

相关推荐

  • javascript - Angularjs .then is not a function - Stack Overflow

    I need to call a Factory method from a Controller method in Angular. But when I call the Factory method

    4小时前
    20

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信