【问题标题】:How to get final redirected url with angularjs's $http如何使用 angularjs 的 $http 获取最终重定向的 url
【发布时间】:2016-09-25 06:47:26
【问题描述】:

有什么方法可以使用 angularjs 的 $http 访问 xhr.responseURL 吗?

MDN 上有一篇文章解释了如何处理原始 xhr。但我找不到任何使用 angularjs 访问 xhr 对象的解决方案。

【问题讨论】:

标签: javascript angularjs xmlhttprequest


【解决方案1】:

我通过修改$xhrFactory找到了解决办法

angular.module('myApp', [])
.factory('$xhrFactory', ['$rootScope', ($rootScope) => {
    return function createXhr(method, url) {

        // configure the xhr object that will be used for $http requests
        const xhr = new window.XMLHttpRequest({ mozSystem: true });

        // attach an handler 
        xhr.onreadystatechange = () => {
            if (xhr.readyState === XMLHttpRequest.DONE) {

                /*
                you can restrict local xhr calls
                if (xhr.responseURL.startsWith('file://')) {
                    return;
                }
                */

                // broadcast xhr object to root scope
                $rootScope.$broadcast('xhrDone', xhr);
            }
        };
        return xhr;
    };
}])
.controller('MyCtrl', ['$scope',  ($scope) => {

    $scope.$on('xhrDone', (event, xhr) => {
        // here is the responseURL
        console.log(xhr.responseURL);
    });

}])

【讨论】:

    【解决方案2】:
    $http.get(...)
        .then(function(response){
            //check response.status/headers/config/statusText
        })
    

    见:https://docs.angularjs.org/api/ng/service/$http

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-07-11
      • 1970-01-01
      • 2014-12-07
      • 2021-09-15
      • 2011-04-03
      • 1970-01-01
      • 2014-02-22
      • 2013-02-03
      相关资源
      最近更新 更多