如果我将 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, fjs);
t._e = [];
t.ready = function(f) {
t._e.push(f);
};
return t;
}(document, 'script', 'twitter-wjs'));
}
}
然后我从中找到了一个可接受的解决方案(Angular 2 上的 Twitter 小部件),但该小部件甚至从第一次加载时就没有显示,也没有错误,所以我什至不知道我错在哪里。
这是永远不会显示 Twitter 小部件且没有任何错误的代码:
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 {
private subscription: Subscription;
constructor(
private route: ActivatedRoute,
private router: Router
) { }
ngOnInit(){}
ngAfterViewInit(){
this.subscription = 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.subscription.unsubscribe();
}
}
基本上,我订阅了小部件数据,NavigationEnd
然后取消订阅它ngOnDestroy
,所以我仍然可以保留路由切换之间的数据。我相信逻辑是正确的,因为该解决方案也适用于某人,但对我来说,直到此刻它才起作用。