Angular2 如何独立于 html base url 设置应用程序根路径

Angular2 how to set app root path independently from html base url

我正在构建一个 angular2 application/widget,它将作为插件嵌入到 TYPO3 中,可以插入任何内容页面。这意味着它可能以不同的根路径结束,例如:

/page1/app
/page/subpage/subpage/whatever

全局基础 url (基础 href=..) 已由 TYPO3 设置,无法更改。我怎样才能给 angular 某种根前缀,以便它可以正确地建立它的路由?

我正在使用此处记录的新路由器:https://angular.io/docs/ts/latest/guide/router.html

原因是您的网络服务器已经在处理 URL,因此它没有委托给 Angular2 路由。要克服这个问题,您必须在 Angular.

中使用不同的 LocationStrategy

您要查找的内容称为 HashLocationStrategy,用于创建类似于 /page1/app/#/angular-controller/ 的路由,其中​​ /page1/app/ 由 Web 服务器提供,而 /angular-controller/ 是第一个参数到您的 Angular2 应用程序逻辑。

调整您的模块声明(例如app.module.ts

import {Component, NgModule} from '@angular/core';
import {
  LocationStrategy,
  HashLocationStrategy
} from '@angular/common';
@NgModule({
  providers: [{provide: LocationStrategy, useClass: HashLocationStrategy}]
})
class AppModule {}

Angular2 documentation 中找到更多详细信息(示例也取自那里)。

我建议不要使用 baseURL 配置属性。它有点过时,会导致一些问题,就像你的一样。

可以设置

config.absRefPrefix = /

现在所有链接都将以 / 开头,并且也可以使用。

实际上 angular 文档中有一个解决方案,但很难找到。可以在 angular 中设置基础 url 而无需使用 <base> 标签。
因此,您只需使用 fluid 将基础 url 设置为全局 JavaScript 变量,然后将其提供给应用程序模块中的 angular。

流体:

<script>
   var app_base_url = '<f:uri.page pageUid="{currentPageUid}" />';
</script>

Angular:

declare var app_base_url;

import {Component, NgModule} from '@angular/core';
import {APP_BASE_HREF} from '@angular/common';
@NgModule({
  providers: [{provide: APP_BASE_HREF, useValue:app_base_url}]
})
class AppModule {}

https://angular.io/docs/ts/latest/api/common/index/APP_BASE_HREF-let.html

看看APP_BASE_HREF这种情况,基本上在Angular2及以上,你可以像这样覆盖提供者,这是Angular.io中的例子展示这种情况:

import {Component, NgModule} from '@angular/core';
import {APP_BASE_HREF} from '@angular/common';
@NgModule({
  providers: [{provide: APP_BASE_HREF, useValue: '/my/app'}]
})
class AppModule {}

所以在那种情况下 APP_BASE_HREF 将被 /my/app 替换,因此您可以分别为每个模块执行此操作...这仅适用于 Angular 应用程序...

有关详细信息,请查看 Angular 文档上的这些页面:

https://angular.io/docs/ts/latest/api/common/index/PathLocationStrategy-class.html

https://angular.io/docs/ts/latest/api/common/index/APP_BASE_HREF-let.html

在最新版本的 angular 中,我收到关于变量的错误,所以我使用 data-attribute 而不是

<body data-base-url="whatever/"> ...

Angular:

import {Component, NgModule} from '@angular/core';
import {APP_BASE_HREF} from '@angular/common';
@NgModule({
  providers: [{provide: APP_BASE_HREF, useValue:documnent.body.dataset.baseUrl}]
})
class AppModule {}