2014-05-05 43 views
0

這是有關模板加載自定義的問題$templateCache

目標是處理傳輸層,正是:

  1. 能夠修改模板URL。
  2. 能夠處理傳輸錯誤和超時。

如何才能$templateCache加載器修改自定義傳輸包裝?

在全球應用程序級別,即指令不應該瞭解此修改。

+2

我想你可以使用一個[裝飾](https://docs.angularjs.org/api/auto/object/$provide#decorator),如任何其他服務。 –

回答

1

你可以使用$http interceptor這個。您可以使用攔截器來更改URL,並使用攔截器來處理錯誤。下面是一個簡單的實現,您將不得不更改爲您希望如何修改URL以及如何處理錯誤。

app.factory('TemplateInterceptor', function($injector, $window, $q, $timeout) { 
    return { 
    'request': function(config) { 
    // Test if is a template 
    var isTemplate = config.url.match(new $window.RegExp("^/?templates/")); 

    // Save in config, so responseError interceptor knows 
    config.TemplateInterceptor = config.TemplateInterceptor || {}; 
    config.TemplateInterceptor.isTemplate = isTemplate; 

    if (isTemplate) { 
     config.url = '/modified-url' + config.url; 
    } 
    return config; 
    }, 
    'responseError': function(rejection) { 
     // Avoid circular dependency issues 
     var $http = $injector.get('$http'); 

     // If a template, then auto-retry after 1 second 
     return !rejection.config.TemplateInterceptor.isTemplate 
     ? $q.reject(rejection) 
     : $timeout(angular.noop, 1000).then(function() { 
     return $http(rejection.config); 
     }); 
    } 
    } 
}); 

註冊爲:

app.config(function($httpProvider) { 
    $httpProvider.interceptors.push('TemplateInterceptor'); 
});