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
3 Answers
Reset to default 3For 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
评论列表(0条)