AngularJS:如何保持在'运行'方法,直到完成
AngularJS: how to stay in 'run' method until it finishes
我有一个简单的场景-我希望用拦截器初始化我的http调用,该拦截器将在header中添加值(某种令牌)。
问题是令牌也是通过http接收的(它应该是第一个调用),但我不知道如何使所有其他调用等待它在发出自己的调用之前完成…
.factory('sessionData', function () {
var currentToken = '[uninitialized-token]';
return {
getToken: function () {
return currentToken;
},
setAuthData: function (token) {
currentToken = token;
}
}
})
.factory('sessionInjector', ['sessionData', function (sessionData) {
var sessionInjector = {
request: function (config) {
console.log("sending with token: " + sessionData.getToken());
config.headers['x-header-sessionID'] = sessionData.getToken();
}
};
return sessionInjector;
}])
.config(['$httpProvider', function ($httpProvider) {
$httpProvider.interceptors.push('sessionInjector');
}])
.run(['$http', 'configs', 'sessionData', function ($http, configs, sessionData) {
$http.get(configs.authApiUrl + 'login').then(function (ret) {
sessionData.setAuthData(ret);
console.log("successfully authenticated with token " + sessionData.getToken());
});
}])
.controller('TestCtrl', function($http){
$scope.p1 = 'Uninitialized';
$http.get('http://localhost/api/getData').then(function(ret){
$scope.p1 = ret;
});
});
问题是TestCtrl
在run
方法完成获取令牌之前发出http调用(导致头值在其值中具有[uninitialized-token])。
如何让控制器等待'运行'异步方法完成?
$http拦截器可以用来在回调中返回承诺。您可以使用它来拦截每个呼叫并将其延迟,直到承诺被解决。
你应该明白承诺是如何工作的。
的例子:
myModule.factory('tokenPromise', function($http) {
return $http.get({url: 'myurl/token', bypassToken: true}).then(function(data) {
// This is when your token webservice return, deal with the response here
return data.token;
});
});
myModule.factory('myHttpInterceptor', function($q, tokenPromise) {
return {
'request': function(config) {
if (config.bypassToken) return config;
// This ensures the token promise is resolved before proceeding with the request.
return tokenPromise.then(function(token) {
config.headers['x-header-sessionID'] = token;
return config;
});
},
};
});
myModule.config(function($httpProvider) {
//wire the interceptor here
$httpProvider.interceptors.push('myHttpInterceptor');
})
reference: HTTP service on angular官方文档
相关文章:
- Meteor方法在客户端返回null,在客户端运行的相同方法返回正确的值
- PhantomJS - 检查javascript函数是否正在运行的任何方法
- 实现比较方法的最佳实践是什么;s的比较类型是在运行时选择的
- Meteor应用程序无法运行-对象#<编译器>没有方法'主机'
- 使用c#在Web服务器上运行JavaScript方法
- strongloop script.js run find in before delete方法:如何同步运行异步方法
- 未能运行构造函数:TypeError:对象#<对象>没有方法'addPlugin'
- 有没有一种方法可以在服务器端页面加载之前在加载时运行javascript
- Chrome扩展:是否有一种方法可以运行JavaScript来获取页面上的内部html,并将其保存到扩展中的变量中
- javascript在html元素方法运行setTimeout后返回此消息
- 为什么可以't我从hamsters.js内部运行我的方法
- 如何从 MVC4 链接调用 Javascript 方法(错误 JavaScript 运行时错误:对象不支持此操作)
- 在客户端 Javascript 方法之后运行服务器方法
- 为什么 then() 链式方法不按顺序运行
- setInterval 只在对象方法上运行一次
- 运行时错误:对象不支持属性或方法
- JQuery .ajax() 函数调用不起作用,但成功方法运行
- 随着时间的推移,JavaScript 的 setInterval() 方法运行是否会消耗明显的处理能力
- javascript方法运行时显示loading.gif
- 将方法c#运行到javascript中