在 Angular 2/4 中使用 Facebook 广告跟踪像素

7

我正在尝试在我的Angular项目中使用Facebook跟踪像素。

我已经将基础像素添加到了我的index.html文件中。

但我想从JavaScript中触发事件,我该如何触发它呢?

fbq('track', 'CompleteRegistration');

当我的代码中存在这个问题,Angular将无法编译,因为它找不到fbq。

3个回答

8
尽管在应用程序运行时,fbq 在全局范围内可用,但编译器不知道它的存在,因为它是在 index.html 中定义的(在编译器已知的 TypeScript 文件之外)。
要解决这个问题,在使用 fbq 的文件中添加一个环境声明,如下所示:
declare const fbq: any; // 1. add an ambient declaration

@Component({...})
export class ComponentUsingFacebookPixel {

  fbq('track', 'CompleteRegistration'); // 2. This will compile now

} 

这不会改变编译后的JavaScript代码,也不会覆盖fbq的值;它只是对编译器的承诺,在运行时会有一个名为该名称的值可用。

如果您想从编译器获得更多帮助,可以提供比any更具体的类型,但是any已足以避免您看到的编译错误。


声明抛出错误。还有其他方法可以实现吗? - SKL
也许可以像 Angular 网站的 Google Analytics 服务 一样使用它,该服务在 index.html 中也定义了一个对象。 - Linh

5

创建一个服务并在 app.component.ts 中调用它。

import { Injectable } from '@angular/core';

    @Injectable({
        providedIn: 'root'
    })
    export class FacebookPixelService {
        constructor() { }
        load() {
            (function (f: any, b, e, v, n, t, s) {
                if (f.fbq) return; n = f.fbq = function () {
                    n.callMethod ?
                        n.callMethod.apply(n, arguments) : n.queue.push(arguments)
                }; if (!f._fbq) f._fbq = n;
                n.push = n; n.loaded = !0; n.version = '2.0'; n.queue = []; t = b.createElement(e); t.async = !0;
                t.src = v; s = b.getElementsByTagName(e)[0]; s.parentNode.insertBefore(t, s)
            })(window, document, 'script', 'https://connect.facebook.net/en_US/fbevents.js');
            (window as any).fbq.disablePushState = true; //not recommended, but can be done
            (window as any).fbq('init', '<your id>');
            (window as any).fbq('track', 'PageView');
        }
    }

2
如果您已经将内容添加到index.html中,请在ngOnInit()中添加此内容。
(window as any).fbq('track', 'CompleteRegistration'); // this Worked for me

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接