【发布时间】:2015-05-16 23:33:44
【问题描述】:
我正在阅读一本名为 MEAN Machine 的书,当我进入最后几章时,我遇到了一个示例应用程序,这似乎不起作用.
问题似乎是因为我的mainController 调用了authService 的Auth.getUser() 方法,该方法可能返回$http.get() 或$q.reject()。由于我没有登录,它返回$q.reject(),并且无法链接.success() 承诺。
它抛出以下异常:
TypeError: undefined is not a function at mainCtrl.js:13
我的代码如下。
控制器mainController
angular.module('mainCtrl', [])
.controller('mainController', function($rootScope, $location, Auth) {
var vm = this;
// check to see if a user is logged in on every request
$rootScope.$on('$routeChangeStart', function () {
vm.loggedIn = Auth.isLoggedIn();
// get user information on route change
Auth.getUser()
/* ========= PROBLEM HERE ========= */
.success(function (data) {
vm.user = data;
});
});
// ... other stuff
});
服务authService
angular.module('authService', [])
// ===================================================
// auth factory to login and get information
// inject $http for communicating with the API
// inject $q to return promise objects
// inject AuthToken to manage tokens
// ===================================================
.factory('Auth', function ($http, $q, AuthToken) {
var authFactory = {};
// get the user info
/* ========= PROBLEM LEADS HERE ========= */
authFactory.getUser = function () {
if (AuthToken.getToken())
return $http.get('/api/me', { cache: true });
else {
return $q.reject({ message: 'User has no token.' });
}
}
我错过了什么?
【问题讨论】:
-
您是否在
Auth中定义了.isLoggedIn()方法? -
嗨@JLRishe。是的,它已经定义了。当它尝试在从 $q.reject() 返回时调用 .success() 时,确实会出现问题。但是感谢您的宝贵时间。
标签: javascript angularjs promise angular-promise