[英]Angular: Social share buttons, update URL for Twitter share button
我用路由组件构建了一个 angular 应用程序。 我尝试添加 Facebook 和 Twitter 共享按钮。 通过 routerlinks 导航到其他组件时,Facebook 和 Twitter 共享按钮会正确更新其 URL。 但是,当导航到已使用其他路由参数激活的同一组件时,Facebook 共享按钮会正确更新 URL,但 Twitter 共享按钮不会。
我已经建立了一个复制品: https://github.com/MintPlayer/SocialShareButtonsAngular
现在您可以对其进行测试: - 上方的分享按钮来自 AppComponent。 导航时它们不会改变。 - 底部的分享按钮位于路由组件中,每次都再次演示正在发生的事情
整个复制品可以在这个存储库中找到: https://github.com/MintPlayer/SocialShareButtonsAngular
已经有基本信息打印到控制台。
在 FacebookShareComponent 和 TwitterShareComponent 内部,有一个 routerLink 输入。 设置 routerLink 时,正在计算 commands 数组。 该数组中的项目也正在使用 IterableDiffers 进行监视。
ngAfterViewChecked() {
const change = this.differ.diff(this.commands);
if (change !== null) {
// console.log(change);
this.updateHref();
this.reloadTwitterWidgets();
}
}
如何更新现有 Twitter 按钮的共享 url? 目前我正在使用 angular 9。
I finally succeeded by just replacing the HTML back to the state required by the Twitter docs, and calling the widgets.load()
function.
export class TwitterShareComponent implements AfterViewChecked {
constructor(private router: Router, private locationStrategy: LocationStrategy, differs: IterableDiffers, @Inject('BASE_URL') private baseUrl: string) {
this.differ = differs.find(this.commands).create(null);
}
@ViewChild('wrapper') wrapper: ElementRef<HTMLDivElement>;
differ: IterableDiffer<any>;
ngAfterViewChecked() {
const change = this.differ.diff(this.commands);
if (change !== null) {
this.updateHref();
this.reloadTwitterWidgets();
}
}
//#region url
href: string;
private commands: any[] = [];
@Input() set routerLink(value: string | any[]) {
if (value === null) {
this.commands = [];
} else if (Array.isArray(value)) {
this.commands = value;
} else {
this.commands = [value];
}
this.updateHref();
this.reloadTwitterWidgets();
}
//#endregion
private updateHref() {
let urlTree = this.router.createUrlTree(this.commands);
let urlSerialized = this.router.serializeUrl(urlTree);
this.href = this.baseUrl + this.locationStrategy.prepareExternalUrl(urlSerialized);
console.log(`Twitter share href: ${this.href}`);
}
private reloadTwitterWidgets() {
if (typeof window !== 'undefined') {
setTimeout(() => {
this.wrapper.nativeElement.innerHTML = `<a href="https://twitter.com/share" class="twitter-share-button" data-url="${this.href}" data-size="${this.size}" data-text="${this.text}" data-count="none">Tweet</a>`;
window['twttr'] && window['twttr'].widgets.load();
}, 10);
}
}
@Input() text: string = '';
@Input() size: 'large' | 'small' = 'large';
}
和 HTML
<div class="wrapper" #wrapper></div>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.