Angular 2+ - 动态设置 base href [英] Angular 2+ - Set base href dynamically
问题描述
我们有一个企业应用程序,客户端使用 Angular 2.我们的每个客户都有自己唯一的网址,例如:https://our.app.com/customer-one
和 https://our.app.com/customer-two代码>.目前,我们可以使用
document.location
动态设置
.所以用户点击 https://our.app.com/customer-two
并且
被设置为 /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
并且他们刷新页面或尝试直接点击该网址,
设置为 /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.
我们尝试了以下方法但无济于事:
We've tried the following to no avail:
<!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.应该是部分
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+ - 动态设置 base href的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!