我创建了一个 Twitter 小部件,并试图将其放入我的 Angular 2 项目中,但 JS 文件不起作用。
如果我用 JS ( Here ) 插入它,它可以工作,但是当我切换到另一个选项卡并返回时(我安装了 Angular Routing)它会消失并显示 A 标签中的任何内容(所以,“Tweets by ...”)。
HTML 代码(在 home 组件中):
<md-card-content>
<a class="twitter-timeline" data-lang="en" data-height="350" data-theme="light" data-chrome="noborders nofooter noheader noscrollbar transparent" href="https://twitter.com/profile">Tweets by profile</a>
</md-card-content>
home.component.ts 中的脚本,代码由@Arg0n 提供(查看答案部分):
import { Component, OnInit } from '@angular/core';
import { Router, NavigationEnd } from '@angular/router';
@Component({
selector: 'app-home',
templateUrl: './home.component.html',
styleUrls: ['./home.component.css']
})
export class HomeComponent implements OnInit {
constructor(private _router : Router) { }
public ngOnInit() {
this._router.events.subscribe(val => {
if (val instanceof NavigationEnd) {
(<any>window).twttr = (function (d, s, id) {
let js: any, fjs = d.getElementsByTagName(s)[0],
t = (<any>window).twttr || {};
if (d.getElementById(id)) return t;
js = d.createElement(s);
js.id = id;
js.src = "https://platform.twitter.com/widgets.js";
fjs.parentNode.insertBefore(js, fjs);
t._e = [];
t.ready = function (f: any) {
t._e.push(f);
};
return t;
}(document, "script", "twitter-wjs"));
twttr.widgets.load();
}
})
}
}
编辑:
好吧,我做了一些研究,发现我必须再次加载小部件,twttr.widgets.load();
但这样做会引发错误。
我编辑了上面的代码,所以你可以看到我尝试了什么。上面的代码返回一个错误:
[ts] Cannot find name 'twttr'
如果我附加(窗口)。对它来说,它向我抛出了这个:
EXCEPTION: Uncaught (in promise): TypeError: Cannot read property 'load' of undefined
关于负载属性的文档在这里:https ://dev.twitter.com/web/javascript/initialization