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

jeck貓
TA貢獻(xiàn)1909條經(jīng)驗(yàn) 獲得超7個(gè)贊
這就是我們最終做的事情。
將其添加到index.html。它應(yīng)該是該<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 關(guān)注
- 2058 瀏覽
添加回答
舉報(bào)
0/150
提交
取消