我正在尝试将<link>
标签添加到页面head
。为此,我创建了一个引导侦听器,并注入了RendererFactory2
并创建了Renderer2的实例:
const renderer: Renderer2 = rendererFactory.createRenderer(document, {
id: 'alternate_link_server_injector',
encapsulation: ViewEncapsulation.None,
styles: [],
data: {}
});
之后,我使用渲染器插入链接:
settingsSelectors.languages$
.pipe(
first(),
switchMap((languages: SettingsLanguage[]) => forkJoin(
languages.map(lang =>
translRouteServ
.translateRoute(router.url, lang)
.pipe(map(url => ({ url, lang })))
)
)),
)
.subscribe(translates => {
appendLinksToHead(translates, renderer, origin, document);
});
...
function appendLinksToHead(
translates: { lang: SettingsLanguage, url: string }[],
renderer: Renderer2,
origin: string,
document: any
) {
Array.from<HTMLLinkElement>(
document.head.querySelectorAll('link[rel="alternate"][hreflang]')
).forEach(el => renderer.removeChild(document.head, el));
translates.forEach(({ url, lang }) => {
const link = renderer.createElement('link');
renderer.setAttribute(link, 'rel', 'alternate');
renderer.setAttribute(link, 'hreflang', lang.language);
renderer.setAttribute(link, 'href', origin + url);
renderer.appendChild(document.head, link);
});
}
在浏览器上一切正常。但是,SSR响应中没有链接。
我记录了以下结果:服务器上的document.head.querySelectorAll('link[rel="alternate"][hreflang]')
,服务器上的document
上存在链接...但是页面源上没有链接...
有人可以帮助我了解原因吗?
更新:
依赖项:
import { DOCUMENT } from '@angular/common';
...
export const alternateLinkInjectorFactoryServerDeps = [
Router,
TranslateRoutesService,
DOCUMENT,
SettingsSelectors,
RendererFactory2,
'ORIGIN_URL'
];