【发布时间】:2017-10-30 04:28:35
【问题描述】:
我见过this post 关于动态设置基本href,但它是为每个客户预定义的基本href。就我而言,我想在用户访问网络应用程序时生成一个随机字符串作为基本 href。例如:
- 在浏览器中访问http://localhost:4200时,重定向到:
http://localhost:4200/{random-string}/home
- 访问http://localhost:4200/home时,也会重定向到:
http://localhost:4200/{random-string}/home
- 在访问http://localhost:4200/{random-string}/home 时,应该保持原样。
了解基础href可以这样设置:
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { APP_BASE_HREF, Location } from '@angular/common';
import { AppComponent } from './';
import { getBaseLocation } from './shared/common-functions.util';
@NgModule({
declarations: [AppComponent],
imports: [
BrowserModule,
HttpModule,
],
bootstrap: [AppComponent],
providers: [
appRoutingProviders,
{
provide: APP_BASE_HREF,
useFactory: getBaseLocation,
deps: [MyService] // Updated based on @Yakov Fain's comment
},
]
})
export class AppModule { }
{random-string} 应该在 getBaseLocation 函数中生成,但我需要将这个 {random-string} 保存在会话中以备将来使用,所以我将 {random-string} 保存到注入到的共享服务中getBaseLocation 是这样的:
export function getBaseLocation(globalService: MyService) {
let paths: string[] = location.pathname.split('/').splice(1, 1);
if (paths && paths[0]) {
// path contains the appId
console.log("Existing appId: " + paths[0]);
// Save appId for future use
globalService.applicationId = paths[0];
} else {
let newAppId = Math.random().toString(36).substr(2, 5);
// Save appId for future use
globalService.applicationId = newAppId;
}
let basePath = globalService.applicationId;
console.log("getBaseLocation : /" + basePath);
return '/' + basePath;
}
访问重定向到 localhost:4200/{random-string}/home 的 localhost:4200 时工作正常。但是,当单击页面上的另一个链接或只是刷新当前页面时,我在浏览器控制台中收到错误。错误是这样的:
GET http://localhost:4200/iun82/1.chunk.js 404(未找到)
ERROR 错误:未捕获(承诺中):错误:加载块 1 失败。
错误:加载块 1 失败。
请指教。谢谢!
【问题讨论】: