我正在尝试在我的Angular项目中使用Facebook跟踪像素。
我已经将基础像素添加到了我的index.html文件中。
但我想从JavaScript中触发事件,我该如何触发它呢?
fbq('track', 'CompleteRegistration');
当我的代码中存在这个问题,Angular将无法编译,因为它找不到fbq。
我正在尝试在我的Angular项目中使用Facebook跟踪像素。
我已经将基础像素添加到了我的index.html文件中。
但我想从JavaScript中触发事件,我该如何触发它呢?
fbq('track', 'CompleteRegistration');
当我的代码中存在这个问题,Angular将无法编译,因为它找不到fbq。
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
已足以避免您看到的编译错误。
创建一个服务并在 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');
}
}
(window as any).fbq('track', 'CompleteRegistration'); // this Worked for me
index.html
中也定义了一个对象。 - Linh