Angular 2/4/5-动态设置基本href [英] Angular 2 / 4 / 5 - Set base href dynamically
问题描述
我们有一个企业应用程序,其客户端使用Angular 2.我们每个客户都有自己的唯一URL,例如:https://our.app.com/customer-one
和https://our.app.com/customer-two
.当前,我们可以使用document.location
动态设置<base href...>
.因此,用户点击https://our.app.com/customer-two
并将<base href...>
设置为/customer-two
...完美!
We have an enterprise app that uses Angular 2 for the client. Each of our customers has their own unique url, ex: https://our.app.com/customer-one
and https://our.app.com/customer-two
. Currently we are able to set the <base href...>
dynamically using document.location
. So user hits https://our.app.com/customer-two
and <base href...>
gets set to /customer-two
...perfect!
问题是,例如,如果用户位于https://our.app.com/customer-two/another-page
,并且他们刷新页面或尝试直接访问该URL,则<base href...>
设置为/customer-two/another-page
,并且找不到资源.
The problem is if the user is for example at https://our.app.com/customer-two/another-page
and they refresh the page or try to hit that url directly, the <base href...>
gets set to /customer-two/another-page
and the resources can't be found.
我们尝试了以下方法:
<!doctype html>
<html>
<head>
<script type='text/javascript'>
var base = document.location.pathname.split('/')[1];
document.write('<base href="/' + base + '" />');
</script>
...
不幸的是,我们对想法一无所知.任何帮助都将是惊人的.
Unfortunately we are fresh out of ideas. Any help would be amazing.
推荐答案
这就是我们最终要做的事情.
Here's what we ended up doing.
将此添加到index.html.这应该是<head>
部分中的第一件事
Add this to index.html. It should be the first thing in the <head>
section
<base href="/">
<script>
(function() {
window['_app_base'] = '/' + window.location.pathname.split('/')[1];
})();
</script>
然后在app.module.ts
文件中,将{ provide: APP_BASE_HREF, useValue: window['_app_base'] || '/' }
添加到提供程序列表中,如下所示:
Then in the app.module.ts
file, add { provide: APP_BASE_HREF, useValue: window['_app_base'] || '/' }
to the list of providers, like so:
import { NgModule, enableProdMode, provide } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { APP_BASE_HREF, Location } from '@angular/common';
import { AppComponent, routing, appRoutingProviders, environment } from './';
if (environment.production) {
enableProdMode();
}
@NgModule({
declarations: [AppComponent],
imports: [
BrowserModule,
HttpModule,
routing],
bootstrap: [AppComponent],
providers: [
appRoutingProviders,
{ provide: APP_BASE_HREF, useValue: window['_app_base'] || '/' },
]
})
export class AppModule { }
这篇关于Angular 2/4/5-动态设置基本href的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!