如何在DSpace 7的UntypedItemComponent.ts中嵌入AddToAny脚本?
解决DSpace 7中AddToAny分享脚本无法生效的问题
问题背景
你熟悉Bootstrap但不了解Angular,在基于Angular重构的DSpace 7系统中,直接将AddToAny分享脚本添加到untyped-item.component.html后无显示效果,需要修改untyped-item.component.ts来让脚本正常工作。
原因说明
Angular组件模板中直接嵌入<script>标签通常不会被执行,这是Angular的安全机制限制。必须通过组件类动态加载脚本,并在视图渲染完成后初始化AddToAny功能。
解决方案步骤
1. 修改HTML模板
将untyped-item.component.html中的**JAVA SCRIPT HERE**替换为AddToAny的DOM结构(移除原脚本标签):
<!-- AddToAny BEGIN --> <div class="a2a_kit a2a_kit_size_32 a2a_default_style"> <a class="a2a_dd" href="https://www.addtoany.com/share"></a> <a class="a2a_button_facebook"></a> <a class="a2a_button_twitter"></a> <a class="a2a_button_email"></a> </div> <!-- AddToAny END -->
2. 更新组件类(.ts文件)
修改untyped-item.component.ts,添加Angular生命周期钩子AfterViewInit,动态加载AddToAny脚本并初始化:
import { ChangeDetectionStrategy, Component, AfterViewInit } from '@angular/core'; import { Item } from '../../../../core/shared/item.model'; import { ViewMode } from '../../../../core/shared/view-mode.model'; import { listableObjectComponent } from '../../../../shared/object-collection/shared/listable-object/listable-object.decorator'; import { VersionedItemComponent } from '../versioned-item/versioned-item.component'; @listableObjectComponent(Item, ViewMode.StandalonePage) @Component({ selector: 'ds-untyped-item', styleUrls: ['./untyped-item.component.scss'], templateUrl: './untyped-item.component.html', changeDetection: ChangeDetectionStrategy.OnPush, }) export class UntypedItemComponent extends VersionedItemComponent implements AfterViewInit { ngAfterViewInit(): void { // 检查脚本是否已加载,避免重复添加 if (!document.querySelector('script[src="https://static.addtoany.com/menu/page.js"]')) { const script = document.createElement('script'); script.src = 'https://static.addtoany.com/menu/page.js'; script.async = true; // 脚本加载完成后初始化AddToAny script.onload = () => { // @ts-ignore 忽略类型检查,因为a2a是全局变量 if (window.a2a) { window.a2a.init_all(); } }; document.body.appendChild(script); } else { // 如果脚本已加载,直接初始化 // @ts-ignore if (window.a2a) { window.a2a.init_all(); } } } }
关键说明
- AfterViewInit钩子:确保在组件视图完全渲染后再加载脚本,此时AddToAny的DOM结构已经存在于页面中。
- 避免重复加载:通过检查页面中是否已存在该脚本标签,防止每次组件初始化都重复添加脚本。
- @ts-ignore注释:因为
window.a2a是AddToAny脚本注入的全局变量,Angular的TypeScript类型系统无法识别,所以添加注释忽略类型错误。
内容的提问来源于stack exchange,提问作者Karol S
相关产品推荐
相关产品推荐

