Hoà*_*yễn 1 twitter angular-routing twitter-widget angular
如果我将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'));
}
}
Run Code Online (Sandbox Code Playgroud)
然后,我从此找到了一个可以接受的解决方案(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();
}
}
Run Code Online (Sandbox Code Playgroud)
基本上,我先订阅窗口小部件数据,NavigationEnd
然后再在中取消订阅ngOnDestroy
,这样我仍然可以保留路由切换之间的数据。我认为该逻辑是正确的,因为该解决方案也适用于某人,但对我而言,直到这一刻才奏效。
试试这个,无需订阅或超时。
ngOnInit() {
(<any>window).twttr.widgets.load();
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
936 次 |
最近记录: |