ExpressJS正在发送以下回复......
res.send('ItemUploaded');
我试图通过拦截器让AngularJS看到这个响应并执行重定向。有没有人有Angular捕获服务器响应的示例代码(例如我的" ItemUploaded")并执行重定向到部分(通过$ location)?
答案 0 :(得分:3)
这很好用。我在我的申请中使用过它。
var interceptor = function ($q, $location) {
return {
request: function (config) {//req
console.log(config);
return config;
},
response: function (result) {//res
console.log('Repos:');
console.log(result.status);
return result;
},
responseError: function (rejection) {//error
console.log('Failed with', rejection.status, 'status');
if (rejection.status == 403) {
$location.url('/dashboard');
}
return $q.reject(rejection);
}
}
};
module.config(function ($httpProvider) {
$httpProvider.interceptors.push(interceptor);
});
答案 1 :(得分:2)
以下是拦截器的工厂:
.factory('InterceptorService',['$q', '$location', function( $q, $location, $http){
var InterceptorServiceFactory = {};
var _request = function(config){
//success logic here
return config;
}
var _responseError = function(rejection) {
//error here. for example server respond with 401
return $q.reject(rejection);
}
InterceptorServiceFactory.request = _request;
InterceptorServiceFactory.responseError = _responseError;
return InterceptorServiceFactory;
}]);
然后注册拦截器:
.config(["$httpProvider", function ($httpProvider) {
$httpProvider.interceptors.push('InterceptorService');
}]);
每个请求都会在这里传递。
答案 2 :(得分:0)
您可以实现一个拦截器工厂,如果它获得匹配的结果将重定向。
angular
.module('app')
.factory("httpinterceptor", ["$location",
function(location) {
return {
'response': function(response) {
if (response.data === "ItemUploaded") {
location.path("/ItemUploaded")
}
}
}
}
]);