动态设置基础href – 角度2
发布时间:2020-12-17 08:20:02 所属栏目:安全 来源:网络整理
导读:我们有一个企业应用程序,客户端使用Angular 2。我们每个客户都有自己独特的网址,例如https://our.app.com/customer-one和https://our.app.com/customer-two。目前,我们可以设置 base href ...动态使用document.location。所以用户点击https://our.app.com
我们有一个企业应用程序,客户端使用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…perfect!
问题是如果用户例如在https://our.app.com/customer-two/another-page,并刷新该页面或尝试直接点击该网址,< base href ...>被设置为/ 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> ... 不幸的是,我们是新鲜的想法。任何帮助将是惊人的。
这是我们最后做的。
将其添加到index.html。应该是< head>中的第一件事部分 <base href="/"> <script> (function() { window['_app_base'] = '/' + window.location.pathname.split('/')[1]; })(); </script> 然后在app.module.ts文件中,添加{提供: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 { } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |