使用angularjs拦截器在工厂外实时发送数据

时间:2019-03-21 04:37:09

标签: angularjs httprequest interceptor

我想解决如何在HTML中使用$scope.time的问题。 我想在UI中显示上一次http请求的时间,但给我一个错误。 我不能使用$scope

我有以下代码:

module.factory('timestamp', [function ($scope) { 
var time = {
    request: function (config) {

        $scope.time = new Date().getTime(); //wanted to show in UI realtime
        return config;
    }
    //,response: function (response) {
    //    response.config.responseTimestamp = new Date().getTime();
    //    return response;
    //}
};
return time;}];

配置:

module.config(function ($httpProvider) {
$httpProvider.interceptors.push('timestamp');}

1 个答案:

答案 0 :(得分:0)

尝试返回$ scope.time或获取任何返回变量而不是config的时间 并尝试访问它

module.factory('timestamp', [function ($scope) { 
var time = {
    request: function (config) {

       config.requestTimestamp = new Date().getTime();
        return config;
    },
    response: function(response) {
        response.config.responseTimestamp = new Date().getTime();
        return response;
    }

};
return time;}];

控制器

module.config(function ($httpProvider) {
$httpProvider.interceptors.push('timestamp');}