【问题标题】:Putting additional data to $routeProvider templateUrl request将附加数据放入 $routeProvider templateUrl 请求
【发布时间】:2015-04-08 01:23:12
【问题描述】:

我想在获取模板的请求中添加一些标头,以便我可以拒绝非 angularjs 请求并以错误响应。

但是,似乎只能使用$http,重新实现类似于templateUrl 提供的机制似乎是一种可怕的浪费。

这是我的示例路由器:

siteApp.config([ '$routeProvider', '$locationProvider',
        function($routeProvider, $locationProvider) {
            $routeProvider.when('/user', {
                controller : 'UserController',
            }).when('/link', {
                templateUrl : '/user/index.json'
            });
            $locationProvider.html5Mode(true);
        } ]);

编辑:如果有帮助,我正在尝试让 ZendFramework2 API 检测到它,但它无法识别 XmlHttpRequest

【问题讨论】:

  • 我个人建议你使用ui-route,它可以默认将$http注入到模板加载中。

标签: javascript angularjs xmlhttprequest angularjs-routing ng-view


【解决方案1】:

我建议您在 angular 的 run 阶段加载这些模板。 这将被放入 $templateCache 提供程序中,当您第二次请求相同的模板时,它将直接从 $templateCache 本身获取。

代码

//get the templates with headers in application run phase.
app.run(['$templateCache', '$q', '$http', function($templateCache, $q, $http) {
    var promises = [];
    $http.get('partials/views/template1.html', {
        headers: {
            'Content-Type': undefined //here you can add multiple header and get the template
        },
        cache: $templateCache
    });
    $http.get('partials/views/template2.html', {
        headers: {
            'Content-Type': undefined //here you can add multiple header and get the template
        },
        cache: $templateCache
    });
}]);

希望这可以帮助你。谢谢。

【讨论】:

  • 非常好的解决方案。有没有办法破解?例如。缓存会以某种方式被刷新?
  • 当然,你可以使用$ templateCache. removeAll(); 清除$templateCache 的所有缓存
猜你喜欢
  • 2012-05-02
  • 2021-09-05
  • 2021-06-04
  • 2021-08-03
  • 1970-01-01
  • 2021-01-04
  • 2021-04-04
  • 2016-03-30
  • 2016-08-15
相关资源
最近更新 更多