[英]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.