【问题标题】:Angular 2 - Set base href with random stringAngular 2 - 使用随机字符串设置基本 href
【发布时间】:2017-10-30 04:28:35
【问题描述】:

我见过this post 关于动态设置基本href,但它是为每个客户预定义的基本href。就我而言,我想在用户访问网络应用程序时生成一个随机字符串作为基本 href。例如:

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 失败。

请指教。谢谢!

【问题讨论】:

    标签: angular angular2-routing


    【解决方案1】:

    如果需要向工厂函数注入服务,请使用以下语法:

      providers: [
        appRoutingProviders,
        provide: MyService, 
        {
            provide: APP_BASE_HREF,
            useFactory: getBaseLocation, deps: [MyService]
        },
      ]
    

    【讨论】:

    • 谢谢雅科夫!但是我在以这种方式实现时收到“未处理的承诺拒绝:url.replace 不是函数”:export function getBaseLocation() { return (svc: MyService): string => { return '/' + randomStr; }}
    • 由于你将一个对象注入到一个函数中,它必须用一个参数来声明,例如getBaseLocation(svc: MyService) {...}
    • 你说得对,雅科夫!然后我遇到了不同的错误。请看我上面更新的帖子。
    • 你的404和延迟加载有关。查看 ng serve 的控制台输出。您的应用程序尝试加载 1.chunk.js(您的延迟加载模块之一),如果您在代码中正确执行所有操作,则 ng serve 命令应该构建一个名为 1.chunk.js 的单独包。
    • 但是ng serve没有错误输出。我需要在 app-routing.ts 中做些什么来满足自定义的 APP_BASE_HREF 吗?
    猜你喜欢
    • 2016-11-01
    • 2019-06-18
    • 1970-01-01
    • 2016-09-12
    • 2014-05-05
    • 1970-01-01
    • 1970-01-01
    • 2019-07-11
    • 1970-01-01
    相关资源
    最近更新 更多