【问题标题】:Twitter widget on Angular 2Angular 2 上的 Twitter 小部件
【发布时间】:2017-08-17 01:24:49
【问题描述】:

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

【问题讨论】:

  • 您应该提供更多信息,如果我们不知道代码,我们应该如何知道如何解决您的问题?
  • 完成了,还有什么需要的吗?
  • 当您以角度切换视图时,twitter 插入的脚本可能不会运行。尝试使用路由器事件再次启动它。

标签: javascript angular angular2-routing twitter-widget


【解决方案1】:

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

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"));
      }
    });
  }
}

【讨论】:

  • 它不起作用,当我在页面之间切换时它不显示推文。
  • 好吧,老实说,这只是一个“可能”的答案。不能测试这个。您在控制台中收到任何错误吗?你能调试并设置一个断点看看会发生什么吗?
  • 好吧,我收到这个错误:syndication.twitter.com/i/jot/……w%22%2C%22page%22%3A%22timeline%22%2C%22action%22%3A%22impression%22%7D%7D加载资源失败:服务器响应状态为 400 () 但我不确定是不是因为您的代码。我现在要调试。
  • 好的,当我切换标签时脚本没有运行。
  • 你从来没有进入过this._router.events.subscribe(val =&gt; { ... });函数?
【解决方案2】:

好的,我找到了解决方案。当我们在 Angular 路由器之间切换时,小部件会卸载。这就是我们放置订阅者的原因,因此我们每次在选项卡之间切换时都会加载小部件。我们可以看到here 如何加载用于延迟加载内容的小部件。当页面准备好时,我们可以使用该函数来加载小部件。视图销毁后别忘了取消订阅!

代码:

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();
  }
}

【讨论】:

  • 我发现删除 Router\NavigationEnd 事件侦听器,而仅使用 ngAfterViewInit 对我来说效果更好,因为在同一路径重新加载浏览器时 NavigationEnd 事件不会触发。不过感谢您的解决方案,帮助我加载!
【解决方案3】:

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

解决方案来自:embedded Twitter widget on Angular 2+ app only shows up on the first page load

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 标记放入模板文件中

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2010-11-24
    • 1970-01-01
    • 1970-01-01
    • 2015-07-15
    • 2019-02-05
    • 2012-06-27
    • 1970-01-01
    • 2016-09-26
    相关资源
    最近更新 更多