2

我创建了一个 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

4

3 回答 3

7

好吧,我找到了解决方案。当我们在 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();
  }
}
于 2017-03-27T14:13:25.383 回答
2

我的评论示例(相关部分):

import { Component, OnInit } from '@angular/core';
import { Router, NavigationEnd } from '@angular/router';

@Component({ ... })
export class MyComponent 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"));
      }
    });
  }
}
于 2017-03-24T08:05:09.707 回答
0

这适用于 angular 7.2.2 和 ionic 4.1。angular 可以构建,ionic 可以构建应用程序并在 cordova 上进行测试。

解决方案来自:Angular 2+ 应用程序上的嵌入式 Twitter 小部件仅在第一页加载时显示

import { Component, OnInit, OnDestroy, AfterViewInit, PLATFORM_ID, Inject } from '@angular/core';
import { isPlatformBrowser } from '@angular/common';

constructor(@Inject(PLATFORM_ID) private platformId: Object) {}

ngAfterViewInit() {
  if (isPlatformBrowser(this.platformId)) {
    setTimeout(function() {
      (<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'));
      (<any>window).twttr.widgets.load();
    }, 100);
  }
}

将 .ts 放在此处并将 twitter 标记放在模板文件中

于 2019-07-11T07:08:43.477 回答