如何在Cordova中加载相对于基本href的XHR请求?

时间:2014-11-13 15:44:14

标签: javascript angularjs cordova

我正在使用AngularJS,我有类似的东西:

myApp.config([
  '$stateProvider', '$urlRouterProvider', '$locationProvider', '$sceProvider', 'appConstants', function($stateProvider, $urlRouterProvider, $locationProvider, $sceProvider, appConstants) {
    $sceProvider.enabled(false);
    $urlRouterProvider.otherwise('/login');
    $stateProvider.state('login', {
      url: '/login',
      templateUrl: "/templates/login.html"
    }).state('tos', {

当它在Cordova中加载时,它会尝试从file:///templates/login.html获取它,但实际上应该从file:///Users/ssiddiqui/Library/Developer/CoreSimulator/Devices/5BFA4F09-2C0A-4916-9D08-21D8BDC9E0A8/data/Containers/Bundle/Application/12B77264-BCB1-4DAA-B1FA-8BC4033ADFAC/HelloWorld.app/www/templates/login.html获取它,因为:

<base href="file:///Users/ssiddiqui/Library/Developer/CoreSimulator/Devices/5BFA4F09-2C0A-4916-9D08-21D8BDC9E0A8/data/Containers/Bundle/Application/12B77264-BCB1-4DAA-B1FA-8BC4033ADFAC/HelloWorld.app/www/">

那么我该如何实现呢?

1 个答案:

答案 0 :(得分:1)

在http-interceptor中,特别是请求拦截器,你可以调整url,如果它以.html结尾

步骤

  1. 获取托管地址

    var hostPath = document.location.pathname.substring(0, document.location.pathname.length - 1);`
    
  2. 如果以.html

    结尾,请更改网址
        if (config.url.indexOf(".html") !== -1) {
            config.url = hostPath + config.url;
        }
    
  3. 完整的请求拦截器看起来像这样

        var requestInterceptor = function (config) {
            var hostPath = document.location.pathname.substring(0, document.location.pathname.length - 1);
            if (config.url.indexOf(".html") !== -1) {
                config.url = hostPath + config.url;
            }
            return config || $q.when(config);
        };
    

    <强> SETUP

    csapp.factory('MyHttpInterceptor', function ($q){
        var requestInterceptor = function (config) {
            var hostPath = document.location.pathname.substring(0, document.location.pathname.length - 1);
            if (config.url.indexOf(".html") !== -1) {
                config.url = hostPath + config.url;
            }
            return config || $q.when(config);
        };
        return {
           request: requestInterceptor
        }
    })
    
    csapp.config(function(){
    
            $httpProvider.interceptors.push('MyHttpInterceptor');
    
    })