【问题标题】:Send data outside the factory real time using angularjs interceptor使用angularjs拦截器实时向厂外发送数据
【发布时间】:2019-03-21 04:37:09
【问题描述】:

我想解决如何在我的 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');}

【问题讨论】:

    标签: angularjs httprequest interceptor


    【解决方案1】:

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

    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');}
    

    【讨论】:

    • 这将在return config 中出错,必须返回配置以便http 请求将通过
    • 是的,我也看到了这个here。问题是如何从其他控制器访问。
    • 我仍然无法访问主控制器中的配置/响应module.controller('MainController', function ($scope,timestamp){ console.log(timestamp.config); });
    • console.log(timestamp.request(config)); console.log(timestamp.request());
    猜你喜欢
    • 1970-01-01
    • 2014-12-23
    • 2014-06-07
    • 1970-01-01
    • 1970-01-01
    • 2019-12-06
    • 1970-01-01
    • 1970-01-01
    • 2014-05-26
    相关资源
    最近更新 更多