【发布时间】:2015-06-03 07:31:04
【问题描述】:
我成功地在我的 Ionic 应用程序中使用了拦截器 (AngularJs)。 Previous post.
虽然它在使用“离子服务”的浏览器中运行良好。
标题标题和内容块(“ion-content”)中没有使用“ionic run android”(在 genymotion 或我自己的手机上模拟)加载任何内容。请看下面的截图。
我很确定它来自我正在使用的拦截器,因为在此之前,该应用程序可以在任何平台上运行。此外,一旦我移除拦截器,它就会再次工作。代码在这里。
请注意,我正在检查调用了哪个 url,因此我不会进入循环依赖或检查无用的 url,只有对我的 api 的调用会通过。
app.config(function($httpProvider){
$httpProvider.interceptors.push(['$location', '$injector', '$q', function($location, $injector, $q){
return {
'request' : function(config){
// intercept request
// carefull includes might not work while emulating
// use instead indexOf for that case
if(!config.url.includes('/oauth/v2/token') && config.url.includes('/api')){
// inject the service manually
var OauthService = $injector.get('OauthService');
var access_token = OauthService.token();
config.url = config.url+'?access_token='+access_token.key;
}
return config;
}
}
}]);
});
任何想法可能会导致此错误? (顺便说一句,控制台在浏览器上没有显示错误)。
更新:
OauthService.js:
app.factory('OauthService', function($http, $localStorage) {
return {
token : function(){
// Store actual token
access_token = $localStorage.getObject('access_token');
// Store actual identity
identity_token = $localStorage.getObject('identity_token');
// IF no user logged
if(isObjectEmpty(identity_token)){
// IF access_token does NOT exist OR will expires soon
if( isObjectEmpty(access_token) || Date.now() > (access_token.expires_at - (600*1000)) ){
// Create an anonymous access_token
return $http
.get(domain+'/oauth/v2/token?client_id='+public_id+'&client_secret='+secret+'&grant_type=client_credentials')
.then(function (response) {
$localStorage.setObject('access_token', {
key: response.data.access_token,
type: 'anonymous',
expires_at: Date.now()+(response.data.expires_in*1000)
});
return response.data.access_token;
});
}
}
// IF user is logged
else{
// IF access_token does NOT exist OR will expires soon OR is anonymous
if( isObjectEmpty(access_token) || Date.now() > (access_token.expires_at - (600*1000)) || access_token.type == 'anonymous' ){
// Create an access_token with an identity
return $http
.get(domain+'/oauth/v2/token?client_id='+public_id+'&client_secret='+secret+'&api_key='+identity_token+'&grant_type=http://oauth2.dev/grants/api_key')
.then(function (response) {
$localStorage.setObject('access_token', {
key: response.data.access_token,
type: 'identity',
expires_at: Date.now()+(response.data.expires_in*1000)
});
return response.data.access_token;
});
}
}
return access_token.key;
}
};
})
【问题讨论】:
-
您是否在
OauthService.token()中返回承诺? -
我不这么认为,我对承诺/延迟的概念有点陌生。我用 OauthService 源代码更新了帖子。
-
但是在第一次启动时它不应该调用 api(登录页面)。所以我们还没有经历这个条件,它已经显示了一个白屏。我想知道拦截器是否没有弄乱我的路线。
-
我猜是的。检查我更新的答案。处理不记名令牌的拦截器应该如何工作有一个粗略的想法。
标签: angularjs cordova ionic-framework ionic