Cha*_*les 6 javascript promise angularjs angular-promise
我正在读一本名为MEAN Machine的书,当我进入后期章节时,我已经陷入其中一个示例应用程序,这似乎不起作用.
问题似乎发生,因为我的mainController调用authService的Auth.getUser()方法,它可能返回a $http.get()或a $q.reject().由于我没有登录,它会返回$q.reject(),并且无法链接.success()承诺.
它抛出以下异常:
TypeError:undefined不是mainCtrl.js中的函数:13
我的代码如下.
CONTROLLERmainController
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
});
Run Code Online (Sandbox Code Playgroud)
服务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.' });
}
}
Run Code Online (Sandbox Code Playgroud)
我错过了什么?
用以下内容替换您对服务的呼叫:
解决方案A .then(successCallback, errorCallback):
Auth.getUser().then(
function (response) { ... }, // success handler
function (response) { // error handler
// case where user is not logged in
// or http request fails
});
Run Code Online (Sandbox Code Playgroud)
要么
解决方案B .then(successCallback).catch(errorCallback):
Auth.getUser()
.then(function (response) { ... }) // success handler
.catch(function (response) { // error handler
// case where user is not logged in
// or http request fails
});
Run Code Online (Sandbox Code Playgroud)
您的getUser方法定义如下:
authFactory.getUser = function () {
if (AuthToken.getToken())
return $http.get('/api/me', { cache: true });
else {
return $q.reject({ message: 'User has no token.' });
}
}
Run Code Online (Sandbox Code Playgroud)
但是success,error速记方法是特定的$http.它们不存在于angular的promise $qAPI中.因此,当用户没有登录时,因为您正在返回一个$q承诺,所以您得到了一个undefined is not a function.
您可以在$qpromise对象上调用的方法是(链接到文档):
then(successCallback, errorCallback, notifyCallback)catch(errorCallback) 这是一个简写 promise.then(null, errorCallback)finally(callback, notifyCallback)| 归档时间: |
|
| 查看次数: |
556 次 |
| 最近记录: |