GTX*_*GTX 2 javascript twitter-widget angular2-routing angular
我创建了一个Twitter小部件,并尝试将其放入Angular 2项目中,但JS文件不起作用。
如果我使用JS(在这里)插入它,则可以使用,但是当我切换到另一个选项卡并返回(我安装了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>
Run Code Online (Sandbox Code Playgroud)
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();
}
})
}
}
Run Code Online (Sandbox Code Playgroud)
编辑:
好的,我进行了一些研究,发现我必须再次加载该小部件,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
好吧,我找到了解决方案。当我们在Angular路由器之间切换时,小部件将卸载。这就是我们放置订户的原因,因此每次在选项卡之间切换时都会加载小部件。我们可以在这里看到如何加载用于延迟加载内容的小部件。页面准备好后,我们可以使用该功能加载小部件。视图毁坏后,别忘了退订!
码:
import { Component, OnDestroy } from '@angular/core';
import { Router, NavigationEnd } from '@angular/router';
@Component({ ... })
export class HomeComponent implements OnDestroy {
private twitter: any;
constructor(private _router: Router) {
this.initTwitterWidget();
}
initTwitterWidget() {
this.twitter = 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"));
if ((<any>window).twttr.ready())
(<any>window).twttr.widgets.load();
}
});
}
ngOnDestroy() {
this.twitter.unsubscribe();
}
}
Run Code Online (Sandbox Code Playgroud)