我创建了一个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 …Run Code Online (Sandbox Code Playgroud) 如果我将Twitter文档(https://dev.twitter.com/web/javascript/loading)中的内置函数完全复制到ngAfterViewInit函数中,则我的应用程序将运行正常,但是当我切换路线时,小部件也会消失。
以下是仅适用于首页加载的代码:
import { Component, OnInit, OnDestroy, AfterViewInit } from '@angular/core';
import { Router, NavigationEnd, ActivatedRoute, ParamMap, Params } from '@angular/router';
import { Observable, Subscription } from 'rxjs/Rx';
export class ProjectDetailComponent implements OnInit, OnDestroy, AfterViewInit {
constructor(
private route: ActivatedRoute,
private router: Router
) { }
ngOnInit(){}
ngAfterViewInit(){
(<any>window).twttr = (function(d, s, id) {
let js, 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, …Run Code Online (Sandbox Code Playgroud)