2

First, I'm new in Angular. I prepare some Web Api and I want get some data from them. my service function get date (works fine):

var _getRole = function () {
    $http.get(serviceBase + 'api/User/CurrentUserRoles').then(function (results) {
        return results;
    });
};

and controller:

var role = [];
authService.getRole().then(function (results) {
     role = results.data;...

In this function in controller I get exception:

TypeError: Cannot read property 'then' of undefined
at n.$scope.login (http://localhost/.../app/controllers/loginController.js:27:30)
at ib.functionCall (http://localhost/.../Scripts/angular.min.js:199:303)
at Ec.(anonymous function).compile.d.on.f (http://localhost/.../Scripts/angular.min.js:216:74)
at n.$get.n.$eval (http://localhost/.../Scripts/angular.min.js:126:15)
at n.$get.n.$apply (http://localhost/.../Scripts/angular.min.js:126:241)
at HTMLButtonElement.<anonymous> (http://localhost/.../Scripts/angular.min.js:216:126)
at HTMLButtonElement.c (http://localhost/.../Scripts/angular.min.js:32:389)

Please help. Thanks.

mar14
  • 85
  • 1
  • 8
  • have you injected `$http` ? – c69 May 02 '15 at 18:14
  • is service - of course, in controller - no – mar14 May 02 '15 at 18:15
  • 1
    ok, now - you are not returning the promise from `_getRole` – c69 May 02 '15 at 18:18
  • I inject and that doesn't help - anything change. – mar14 May 02 '15 at 18:21
  • I've got something like this before: var deferred = $q.defer(); deferred.resolve(results); return deferred.promise; anythink change - exception still there – mar14 May 02 '15 at 18:23
  • possible duplicate of [Angularjs/Ionic TypeError: Cannot read property 'then' of undefined](http://stackoverflow.com/questions/28209744/angularjs-ionic-typeerror-cannot-read-property-then-of-undefined) – c69 May 02 '15 at 18:23
  • 1
    @c69 duplicate answer is telling to create custom promise & returning that custom promise..I would not prefer that way...you could look at my answer..that is reusing promise return by `$http` – Pankaj Parkar May 02 '15 at 18:30
  • Yes, just adding return is enough. But that's stated in the last part of the accepted answer to the linked question. – c69 May 02 '15 at 18:32
  • 1
    `.then(function (results) { return results; });` looks totally superfluous? Remove it. – Bergi May 02 '15 at 18:37
  • @Bergi thanks for edit, it was really of no meaning :) – Pankaj Parkar May 02 '15 at 19:04

1 Answers1

2

You need to return promise from function that $http does return itself.

Code

var _getRole = function () {
    return $http.get(serviceBase + 'api/User/CurrentUserRoles');
};
Bergi
  • 630,263
  • 148
  • 957
  • 1,375
Pankaj Parkar
  • 134,766
  • 23
  • 234
  • 299