在Angular应用中使用服务器渲染的html的演练



不幸的是,我们有一个用AngularJS运行的多页面应用。现在,随着LTS的临近,我们正在尝试迁移到Angular。我们过去用服务器数据填充模板的某些部分,将html呈现如下:

<div class="some-class" ng-controller="SomeCtrl as ctrl">
<div>...</div> <!-- Render some data from server -->
<div sec:authorize="isRememberMe()">...</div> <!-- Use some Thymeleaf security tags -->
</div>

但是,既然组件已经在客户端上,我正在寻找使用服务器呈现的html操作模板的方法。我已经尝试了ng-content,这在某些情况下是有用的,在那里我可以在app-root之外引导组件本身,就像在主应用程序之外的渲染Angular组件。但是当模板在组件本身时,这种能力也消失了。

另一种选择是将页面呈现为非Angular的常规html页面(而不是组件),并访问Angular可以提供的一些基本功能。我们过去使用的方法也允许这一点,但我不知道如何才能实现这一点。

有我要找的东西吗?

我想到的是:

用thyymleaf渲染index.html:

<!DOCTYPE html>
<html lang="en"
xmlns:th="http://www.thymeleaf.org">
<head th:replace="partials/head :: head"></head>
<body>
<th:block th:replace="partials/header :: header"></th:block>
<app-root th:attr="some-property=${some.value.from.model}"></app-root>
<th:block th:replace="partials/footer :: footer"></th:block>
</body>

这将渲染:

<!DOCTYPE html>
<html lang="en"
xmlns:th="http://www.thymeleaf.org">
<head>
...
</head>
<body>
...
<app-root some-property="some-value"></app-root>
...
</body>

创建data.service.ts:

appData: any = {};

app.component.ts:

constructor(private dataService: DataService,
private element: ElementRef) {
}
ngOnInit(): void {
this.dataService.appData['some-property'] = this.element.nativeElement.getAttribute('some-property');
}

最后在sub.component.ts:

constructor(private dataService: DataService) {
}
ngOnInit(): void {
this.someProperty = this.dataService.appData['some-property'];
}

最新更新