javascript Angular JS:如何通过 $http 为所有调用设置上下文路径?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19282092/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 14:59:13  来源:igfitidea点击:

Angular JS: How to set context path for all calls through $http?

javascriptangularjs

提问by Konrad Garus

I'm deploying my Angular application in a web server, where the app may live at http://localhost:8080/app-name, or http://foobars.com/, or some other URL. I do not have any guarantees about the absolute path - sometimes the call may need to go to /app-name/foo, sometimes to /foo, sometimes to /foobars/foo. In other words, there is a moving part: /app-name, (empty), /foobarsin samples above. Also known as context path.

我正在 Web 服务器中部署我的 Angular 应用程序,该应用程序可能位于http://localhost:8080/app-name、 或http://foobars.com/或其他某个 URL。我对绝对路径没有任何保证 - 有时调用可能需要转到/app-name/foo,有时到/foo,有时到/foobars/foo。换句话说,在上面的示例中有一个移动部分:/app-name, (empty), /foobars。也称为上下文路径。

I know I can use <base>for HTML. I can wrap $httpor configure Restangular to prepend context path for all calls.

我知道我可以<base>用于 HTML。我可以包装$http或配置 Restangular 来为所有调用添加上下文路径。

But there still are cases that I don't yet know how to address. For instance, whenever directive uses a template, it is loaded via bare $httpas well.

但仍有一些情况我还不知道如何处理。例如,每当指令使用模板时,它也会通过裸加载$http

How can I get $httpto always use some specific base path for all requests?

我怎样才能$http始终为所有请求使用一些特定的基本路径?

采纳答案by Erstad.Stephen

You will want to configure the $httpProvider to use an Interceptor that modifies the config that the call to $http will use.

您需要将 $httpProvider 配置为使用拦截器来修改调用 $http 将使用的配置。

See the Interceptors section here: http://docs.angularjs.org/api/ng.$http

请参阅此处的拦截器部分:http: //docs.angularjs.org/api/ng.$http

This will allow you to control your contextual path in any way you need for all $http calls.

这将允许您以任何方式控制所有 $http 调用所需的上下文路径。