Angular 2/4/5 - 動態設置基本href我們有一個企業應用程序,它為客戶端使用Angular 2。我們每個客戶都有自己獨特的網址,例如:https://our.app.com/customer-one和https://our.app.com/customer-two。目前我們可以<base href...>動態設置document.location。所以用戶點擊https://our.app.com/customer-two并<base href...>設置為/customer-two......完美!問題是,如果用戶是例如,https://our.app.com/customer-two/another-page并且他們刷新頁面或嘗試直接點擊該URL,則<base href...>設置為get /customer-two/another-page并且找不到資源。我們嘗試了以下無濟于事:<!doctype html><html><head>
<script type='text/javascript'>
var base = document.location.pathname.split('/')[1];
document.write('<base href="/' + base + '" />');
</script>...不幸的是,我們的想法很新鮮。任何幫助都會很棒。
3 回答

jeck貓
TA貢獻1909條經驗 獲得超7個贊
這就是我們最終做的事情。
將其添加到index.html。它應該是該<head>
部分的第一件事
<base href="/"><script> (function() { window['_app_base'] = '/' + window.location.pathname.split('/')[1]; })();</script>
然后在app.module.ts
文件中,添加{ provide: APP_BASE_HREF, useValue: window['_app_base'] || '/' }
到提供程序列表,如下所示:
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 { }
- 3 回答
- 0 關注
- 2059 瀏覽
添加回答
舉報
0/150
提交
取消