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

Jam*_*wis 4 javascript facebook angular

我正在尝试找出如何在我的角度项目中使用Facebook跟踪像素。

我已将基本像素添加到我的index.html中

但我想通过javascript触发事件,如何触发

fbq('track','CompleteRegistration');

当我在我的代码中有此功能时,Angular将无法编译,因为它找不到fbq

小智 6

即使fbq在运行时在您的应用程序中全局可用,编译器也不知道它,因为它是在index.html(在编译器已知的打字稿文件之外)定义的。

要解决此问题,请将环境声明添加到您使用的文件中fbq,如下所示:

declare const fbq: any; // 1. add an ambient declaration

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

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

} 
Run Code Online (Sandbox Code Playgroud)

这不会更改已编译的javascript或覆盖fbq; 的值;向编译器保证在运行时将提供该名称的值。

any您希望从编译器获得其他帮助相比,您可以提供更具体的类型,但any足以避免您看到的编译错误。


Sou*_*Raj 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');
        }
    }
Run Code Online (Sandbox Code Playgroud)