Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/angularjs/25.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Angularjs 角度-http拦截器+;异步调用_Angularjs_Interceptor - Fatal编程技术网

Angularjs 角度-http拦截器+;异步调用

Angularjs 角度-http拦截器+;异步调用,angularjs,interceptor,Angularjs,Interceptor,我试图理解如何在Ansible 1.5.3中编写httpInterceptor 基于 现在我不明白如何编写MyService(它执行GET) 我试图添加myconfig函数,但在循环依赖中迷失了方向: $provide.factory('MyService', function($injector) { var MyService = { async: function() { // $http returns a promise, whi

我试图理解如何在Ansible 1.5.3中编写httpInterceptor

基于

现在我不明白如何编写MyService(它执行GET)

我试图添加myconfig函数,但在循环依赖中迷失了方向:

    $provide.factory('MyService', function($injector) {
      var MyService = {
        async: function() {
          // $http returns a promise, which has a then function, which also returns a promise
          console.log("CIAO")
            var $http = $injector.get('$http');
            var promise = $http.get('refresh_token.json').then(function (response) {
            // The then function here is an opportunity to modify the response
            console.log(response);
            // The return value gets picked up by the then in the controller.
            return response.data;
          });
          // Return the promise to the controller
          return promise;
        }
      };
      return MyService;
    })
有人能帮我吗


Riccardo正在分享我的工作方案。也许NodeJS大师可以验证

(function() {
'use strict';

angular
    .module('app', ['ui.router', 'ngStorage', 'angular-loading-bar', 'angular-jwt'])                
    .config(myconfig)
    .run(myrun);

function myconfig($stateProvider, $urlRouterProvider, $provide, $httpProvider) {
    ...
    // ----------------------------------------------------------------------
    // Interceptor HTTP request
    // ----------------------------------------------------------------------       
    $provide.factory('MyService', function($injector, $localStorage) {
        var MyService = {
            async: function() {
                // $http returns a promise, which has a then function, which also returns a promise
                //console.log("STO PER FARE UNA CHIAMATA ASINCRONA!!!")
                var $http = $injector.get('$http');
                console.log("REFRESHTOKEN DA INVIARE: " + $localStorage.currentUser.refreshToken)
                // La POST va fatta con x-www-form-urlencoded al fine di evitare CORS
                var promise = $http({
                    method: 'POST',
                    headers: { 
                       'Authorization': undefined,
                       'Content-Type': 'application/x-www-form-urlencoded'
                    },
                    url: "https://xxxxxxxxxx/v1/refreshToken",
                    transformRequest: function(obj) {
                         var str = [];
                         for(var p in obj)
                         str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p]));
                         return str.join("&");
                     },
                     data: {
                        "refreshToken": $localStorage.currentUser.refreshToken
                    }
                }).then(function(response) {
                    // The then function here is an opportunity to modify the response
                    // console.log(response);
                    // The return value gets picked up by the then in the controller.
                    return response.data;
                });
                // Return the promise to the controller
                return promise;
            }
        };
        return MyService;
    })

    $provide.factory('httpRequestInterceptor', ['$q', "MyService", "$localStorage", "jwtHelper", '$injector', function($q, MyService, $localStorage, jwtHelper, $injector) {
        return {
            'request': function(config) {
                if (config.url.indexOf("/v1/refreshToken") >= 0) {
                    /* Se la request e' generata verso l'endpoint di refreshToken
                       allora salta l'interceptor al fine di evitare dipendenze circolari */
                    console.log("INFO1: SKIP " + config.url);
                    return config;
                } else if (config.url.indexOf(".html") >= 0) {
                    /* Se e' l'include di una view, salta l'inteceptor */
                    console.log("INFO2: SKIP " + config.url);
                    return config;
                } else if (!$localStorage.currentUser || !$localStorage.currentUser.refreshToken) {
                    /* Se non c'e' una sessione aperta oppure la sessione non prevede refresh 
                       allora salta l'interceptor */
                    console.log("INFO3: SKIP nessun token");
                    return config;
                } else if ($localStorage.currentUser.refresh_in_corso == true) {
                    /* Se ci sono diverse chiamate Ajax solo la prima viene fermata.
                       Infatti, visto che l'accessToken non e' del tutto scaduto,
                       e' possibile far coesistire per qualche istante il vecchio 
                       accessToken con quello nuovo ottenuto dal processo di refresh */
                    console.log("INFO4: SKIP refresh in corso");
                    return config;    
                } else {
                    var $http = $injector.get('$http');
                    var guard_period = 5 * 60 // seconds
                    var current_timestamp = Math.floor(Date.now() / 1000);
                    var exp_timestamp_guard = $localStorage.currentUser.exp - guard_period
                    console.log("NEEDREFRESH" + exp_timestamp_guard + "  -->  " + new Date(exp_timestamp_guard * 1000))
                    console.log("NOW        " + current_timestamp + "  -->  " + new Date(current_timestamp * 1000))
                    if (current_timestamp <= exp_timestamp_guard) {
                        console.log("INFO5: SKIP non in zona critica");
                        return config;    
                    } else {
                        console.log("INFO6: refresh necessario")
                        $localStorage.currentUser.refresh_in_corso = true;
                        /* Si è nella zona prossima allo scadere del token di accesso
                           E' possibile richiedere il refresh */
                        console.log("Sono in config: " + config.url + " e apro una chiamata async")
                        var deferred = $q.defer();
                        MyService.async().then(function(mydata) {
                            console.log("Funzione asincrona terminata con successo")
                            // Asynchronous operation succeeded, modify config accordingly                                
                            try {
                                 var plainPayload = jwtHelper.decodeToken(mydata.accessToken);
                                 // store useruid and token in local storage to keep user logged in between page refreshes
                                 $localStorage.currentUser = {
                                     userUid: plainPayload.usr.uid,
                                     systemName: plainPayload.usr.sn,
                                     exp: plainPayload.exp,
                                     accessToken: mydata.accessToken,
                                     refreshToken: mydata.refreshToken,
                                     user: mydata.user,
                                     refresh_in_corso: true
                                 };                  

                                 // add jwt token to auth header for all requests made by the $http service
                                 $http.defaults.headers.common.Authorization = 'Bearer ' + mydata.accessToken;

                                 $localStorage.currentUser.refresh_in_corso = false;

                                 console.log("NUOVO HEADER AUTH: " + $http.defaults.headers.common.Authorization)
                            }
                            catch (err) {
                                $localStorage.currentUser.refresh_in_corso = false;
                                console.log("Token errato. Il refresh non sara' possibile: " + err)
                            }
                            deferred.resolve(config);
                        }, function() {
                            // Asynchronous operation failed, modify config accordingly
                            console.log("Async KO")
                            deferred.resolve(config);
                        });
                        return deferred.promise;
                    }
                }
            }
        };
    }]);
    $httpProvider.interceptors.push('httpRequestInterceptor');
}
里卡多

(function() {
'use strict';

angular
    .module('app', ['ui.router', 'ngStorage', 'angular-loading-bar', 'angular-jwt'])                
    .config(myconfig)
    .run(myrun);

function myconfig($stateProvider, $urlRouterProvider, $provide, $httpProvider) {
    ...
    // ----------------------------------------------------------------------
    // Interceptor HTTP request
    // ----------------------------------------------------------------------       
    $provide.factory('MyService', function($injector, $localStorage) {
        var MyService = {
            async: function() {
                // $http returns a promise, which has a then function, which also returns a promise
                //console.log("STO PER FARE UNA CHIAMATA ASINCRONA!!!")
                var $http = $injector.get('$http');
                console.log("REFRESHTOKEN DA INVIARE: " + $localStorage.currentUser.refreshToken)
                // La POST va fatta con x-www-form-urlencoded al fine di evitare CORS
                var promise = $http({
                    method: 'POST',
                    headers: { 
                       'Authorization': undefined,
                       'Content-Type': 'application/x-www-form-urlencoded'
                    },
                    url: "https://xxxxxxxxxx/v1/refreshToken",
                    transformRequest: function(obj) {
                         var str = [];
                         for(var p in obj)
                         str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p]));
                         return str.join("&");
                     },
                     data: {
                        "refreshToken": $localStorage.currentUser.refreshToken
                    }
                }).then(function(response) {
                    // The then function here is an opportunity to modify the response
                    // console.log(response);
                    // The return value gets picked up by the then in the controller.
                    return response.data;
                });
                // Return the promise to the controller
                return promise;
            }
        };
        return MyService;
    })

    $provide.factory('httpRequestInterceptor', ['$q', "MyService", "$localStorage", "jwtHelper", '$injector', function($q, MyService, $localStorage, jwtHelper, $injector) {
        return {
            'request': function(config) {
                if (config.url.indexOf("/v1/refreshToken") >= 0) {
                    /* Se la request e' generata verso l'endpoint di refreshToken
                       allora salta l'interceptor al fine di evitare dipendenze circolari */
                    console.log("INFO1: SKIP " + config.url);
                    return config;
                } else if (config.url.indexOf(".html") >= 0) {
                    /* Se e' l'include di una view, salta l'inteceptor */
                    console.log("INFO2: SKIP " + config.url);
                    return config;
                } else if (!$localStorage.currentUser || !$localStorage.currentUser.refreshToken) {
                    /* Se non c'e' una sessione aperta oppure la sessione non prevede refresh 
                       allora salta l'interceptor */
                    console.log("INFO3: SKIP nessun token");
                    return config;
                } else if ($localStorage.currentUser.refresh_in_corso == true) {
                    /* Se ci sono diverse chiamate Ajax solo la prima viene fermata.
                       Infatti, visto che l'accessToken non e' del tutto scaduto,
                       e' possibile far coesistire per qualche istante il vecchio 
                       accessToken con quello nuovo ottenuto dal processo di refresh */
                    console.log("INFO4: SKIP refresh in corso");
                    return config;    
                } else {
                    var $http = $injector.get('$http');
                    var guard_period = 5 * 60 // seconds
                    var current_timestamp = Math.floor(Date.now() / 1000);
                    var exp_timestamp_guard = $localStorage.currentUser.exp - guard_period
                    console.log("NEEDREFRESH" + exp_timestamp_guard + "  -->  " + new Date(exp_timestamp_guard * 1000))
                    console.log("NOW        " + current_timestamp + "  -->  " + new Date(current_timestamp * 1000))
                    if (current_timestamp <= exp_timestamp_guard) {
                        console.log("INFO5: SKIP non in zona critica");
                        return config;    
                    } else {
                        console.log("INFO6: refresh necessario")
                        $localStorage.currentUser.refresh_in_corso = true;
                        /* Si è nella zona prossima allo scadere del token di accesso
                           E' possibile richiedere il refresh */
                        console.log("Sono in config: " + config.url + " e apro una chiamata async")
                        var deferred = $q.defer();
                        MyService.async().then(function(mydata) {
                            console.log("Funzione asincrona terminata con successo")
                            // Asynchronous operation succeeded, modify config accordingly                                
                            try {
                                 var plainPayload = jwtHelper.decodeToken(mydata.accessToken);
                                 // store useruid and token in local storage to keep user logged in between page refreshes
                                 $localStorage.currentUser = {
                                     userUid: plainPayload.usr.uid,
                                     systemName: plainPayload.usr.sn,
                                     exp: plainPayload.exp,
                                     accessToken: mydata.accessToken,
                                     refreshToken: mydata.refreshToken,
                                     user: mydata.user,
                                     refresh_in_corso: true
                                 };                  

                                 // add jwt token to auth header for all requests made by the $http service
                                 $http.defaults.headers.common.Authorization = 'Bearer ' + mydata.accessToken;

                                 $localStorage.currentUser.refresh_in_corso = false;

                                 console.log("NUOVO HEADER AUTH: " + $http.defaults.headers.common.Authorization)
                            }
                            catch (err) {
                                $localStorage.currentUser.refresh_in_corso = false;
                                console.log("Token errato. Il refresh non sara' possibile: " + err)
                            }
                            deferred.resolve(config);
                        }, function() {
                            // Asynchronous operation failed, modify config accordingly
                            console.log("Async KO")
                            deferred.resolve(config);
                        });
                        return deferred.promise;
                    }
                }
            }
        };
    }]);
    $httpProvider.interceptors.push('httpRequestInterceptor');
}
(函数(){
"严格使用",;
有棱角的
.module('app',['ui.router','ngStorage','angular loading bar','angular jwt']))
.config(myconfig)
.run(myrun);
函数myconfig($stateProvider、$urlRouterProvider、$provide、$httpProvider){
...
// ----------------------------------------------------------------------
//侦听器HTTP请求
// ----------------------------------------------------------------------       
$provide.factory('MyService',函数($injector,$localStorage){
var MyService={
异步:函数(){
//$http返回一个承诺,它有一个then函数,该函数也返回一个承诺
//console.log(“每车费加运费!!!”)
var$http=$injector.get('$http');
log(“REFRESHTOKEN:+$localStorage.currentUser.REFRESHTOKEN”)
//《法塔邮报》x-www-form-urlencoded al fine di evitare CORS
var promise=$http({
方法:“POST”,
标题:{
“授权”:未定义,
“内容类型”:“应用程序/x-www-form-urlencoded”
},
url:“https://xxxxxxxxxx/v1/refreshToken",
转换请求:功能(obj){
var-str=[];
用于(obj中的var p)
str.push(encodeURIComponent(p)+“=”+encodeURIComponent(obj[p]));
返回str.join(“&”);
},
数据:{
“refreshToken”:$localStorage.currentUser.refreshToken
}
}).然后(功能(响应){
//此处的then函数是修改响应的机会
//控制台日志(响应);
//返回值由控制器中的then获取。
返回响应数据;
});
//将承诺返还给控制者
回报承诺;
}
};
返回MyService;
})
$provide.factory('httpRequestInterceptor'、['$q'、'MyService'、“$localStorage”、“jwtHelper”、'$injector',函数($q、MyService、$localStorage、jwtHelper、$injector){
返回{
“请求”:函数(配置){
if(config.url.indexOf(“/v1/refreshttoken”)>=0{
/*Se la请求e'Genera verso l'endpoint di refreshToken
阿洛拉·萨尔塔·阿洛拉·萨尔塔·阿洛拉·萨尔塔·阿洛拉·阿洛拉·萨尔塔·阿洛拉·阿洛拉·阿洛拉·萨尔塔·阿洛拉·阿洛拉·萨尔塔·阿洛拉·阿洛拉·阿*/
log(“INFO1:SKIP”+config.url);
返回配置;
}else if(config.url.indexOf(“.html”)>=0){
/*这包括我的观点,我的接受者*/
log(“INFO2:SKIP”+config.url);
返回配置;
}else if(!$localStorage.currentUser | |!$localStorage.currentUser.refreshToken){
/*这是一个无需事先刷新的会话
阿洛拉·萨尔塔拦截器*/
log(“INFO3:跳过nessun令牌”);
返回配置;
}else if($localStorage.currentUser.refresh\u in\u corso==true){
/*这是一个多样化的交叉阿贾克斯独奏曲。
因法蒂,维斯托·切勒·卡杜托,
在维奇奥的每个码头都可能有一个共同的建筑
accessToken con quello nuovo ottenuto dal processo di refresh*/
log(“INFO4:跳过corso中的刷新”);
返回配置;
}否则{
var$http=$injector.get('$http');
var保护周期=5*60//s
var current_timestamp=Math.floor(Date.now()/1000);
var exp\u timestamp\u guard=$localStorage.currentUser.exp-guard\u period
log(“NEEDREFRESH”+exp\u timestamp\u guard+“-->”+新日期(exp\u timestamp\u guard*1000))
log(“现在”+当前时间戳+“-->”+新日期(当前时间戳*1000))

如果(当前时间戳只是分享我的工作解决方案。也许NodeJS专家可以验证

里卡多

(function() {
'use strict';

angular
    .module('app', ['ui.router', 'ngStorage', 'angular-loading-bar', 'angular-jwt'])                
    .config(myconfig)
    .run(myrun);

function myconfig($stateProvider, $urlRouterProvider, $provide, $httpProvider) {
    ...
    // ----------------------------------------------------------------------
    // Interceptor HTTP request
    // ----------------------------------------------------------------------       
    $provide.factory('MyService', function($injector, $localStorage) {
        var MyService = {
            async: function() {
                // $http returns a promise, which has a then function, which also returns a promise
                //console.log("STO PER FARE UNA CHIAMATA ASINCRONA!!!")
                var $http = $injector.get('$http');
                console.log("REFRESHTOKEN DA INVIARE: " + $localStorage.currentUser.refreshToken)
                // La POST va fatta con x-www-form-urlencoded al fine di evitare CORS
                var promise = $http({
                    method: 'POST',
                    headers: { 
                       'Authorization': undefined,
                       'Content-Type': 'application/x-www-form-urlencoded'
                    },
                    url: "https://xxxxxxxxxx/v1/refreshToken",
                    transformRequest: function(obj) {
                         var str = [];
                         for(var p in obj)
                         str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p]));
                         return str.join("&");
                     },
                     data: {
                        "refreshToken": $localStorage.currentUser.refreshToken
                    }
                }).then(function(response) {
                    // The then function here is an opportunity to modify the response
                    // console.log(response);
                    // The return value gets picked up by the then in the controller.
                    return response.data;
                });
                // Return the promise to the controller
                return promise;
            }
        };
        return MyService;
    })

    $provide.factory('httpRequestInterceptor', ['$q', "MyService", "$localStorage", "jwtHelper", '$injector', function($q, MyService, $localStorage, jwtHelper, $injector) {
        return {
            'request': function(config) {
                if (config.url.indexOf("/v1/refreshToken") >= 0) {
                    /* Se la request e' generata verso l'endpoint di refreshToken
                       allora salta l'interceptor al fine di evitare dipendenze circolari */
                    console.log("INFO1: SKIP " + config.url);
                    return config;
                } else if (config.url.indexOf(".html") >= 0) {
                    /* Se e' l'include di una view, salta l'inteceptor */
                    console.log("INFO2: SKIP " + config.url);
                    return config;
                } else if (!$localStorage.currentUser || !$localStorage.currentUser.refreshToken) {
                    /* Se non c'e' una sessione aperta oppure la sessione non prevede refresh 
                       allora salta l'interceptor */
                    console.log("INFO3: SKIP nessun token");
                    return config;
                } else if ($localStorage.currentUser.refresh_in_corso == true) {
                    /* Se ci sono diverse chiamate Ajax solo la prima viene fermata.
                       Infatti, visto che l'accessToken non e' del tutto scaduto,
                       e' possibile far coesistire per qualche istante il vecchio 
                       accessToken con quello nuovo ottenuto dal processo di refresh */
                    console.log("INFO4: SKIP refresh in corso");
                    return config;    
                } else {
                    var $http = $injector.get('$http');
                    var guard_period = 5 * 60 // seconds
                    var current_timestamp = Math.floor(Date.now() / 1000);
                    var exp_timestamp_guard = $localStorage.currentUser.exp - guard_period
                    console.log("NEEDREFRESH" + exp_timestamp_guard + "  -->  " + new Date(exp_timestamp_guard * 1000))
                    console.log("NOW        " + current_timestamp + "  -->  " + new Date(current_timestamp * 1000))
                    if (current_timestamp <= exp_timestamp_guard) {
                        console.log("INFO5: SKIP non in zona critica");
                        return config;    
                    } else {
                        console.log("INFO6: refresh necessario")
                        $localStorage.currentUser.refresh_in_corso = true;
                        /* Si è nella zona prossima allo scadere del token di accesso
                           E' possibile richiedere il refresh */
                        console.log("Sono in config: " + config.url + " e apro una chiamata async")
                        var deferred = $q.defer();
                        MyService.async().then(function(mydata) {
                            console.log("Funzione asincrona terminata con successo")
                            // Asynchronous operation succeeded, modify config accordingly                                
                            try {
                                 var plainPayload = jwtHelper.decodeToken(mydata.accessToken);
                                 // store useruid and token in local storage to keep user logged in between page refreshes
                                 $localStorage.currentUser = {
                                     userUid: plainPayload.usr.uid,
                                     systemName: plainPayload.usr.sn,
                                     exp: plainPayload.exp,
                                     accessToken: mydata.accessToken,
                                     refreshToken: mydata.refreshToken,
                                     user: mydata.user,
                                     refresh_in_corso: true
                                 };                  

                                 // add jwt token to auth header for all requests made by the $http service
                                 $http.defaults.headers.common.Authorization = 'Bearer ' + mydata.accessToken;

                                 $localStorage.currentUser.refresh_in_corso = false;

                                 console.log("NUOVO HEADER AUTH: " + $http.defaults.headers.common.Authorization)
                            }
                            catch (err) {
                                $localStorage.currentUser.refresh_in_corso = false;
                                console.log("Token errato. Il refresh non sara' possibile: " + err)
                            }
                            deferred.resolve(config);
                        }, function() {
                            // Asynchronous operation failed, modify config accordingly
                            console.log("Async KO")
                            deferred.resolve(config);
                        });
                        return deferred.promise;
                    }
                }
            }
        };
    }]);
    $httpProvider.interceptors.push('httpRequestInterceptor');
}
(函数(){
"严格使用",;
有棱角的
.module('app',['ui.router','ngStorage','angular loading bar','angular jwt']))
.config(myconfig)
.run(myrun);
函数myconfig($stateProvider、$urlRouterProvider、$provide、$httpProvider){
...
// ----------------------------------------------------------------------
//侦听器HTTP请求
// ----------------------------------------------------------------------       
$provide.factory('MyService',函数($injector,$localStorage){
var MyService={
异步:函数(){
//$http返回一个承诺,它有一个then函数,该函数也返回一个承诺
//console.log(“每车费加运费!!!”)
var$http=$injector.get('$http');
log(“REFRESHTOKEN:+$localStorage.currentUser.REFRESHTOKEN”)
//《法塔邮报》x-www-form-urlencoded al fine di evitare COR