如何在Angular中实现Facebook像素? [英] How to implement a facebook pixel in Angular?

查看:90
本文介绍了如何在Angular中实现Facebook像素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要在一个有角的项目中实现一个facebook像素.我在 src/index.html

I need to implement a facebook pixel in an angular proyect. I have the pixel in my index.html from src/index.html

<!doctype html>
<html lang="en">
  <head>
  .....
  </head>

<body>
  <app-root></app-root>
  <!-- Facebook Pixel Code -->
  <script>
    !function(f,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');
    fbq('init', 'XXXXXXXXXXXXX');
    fbq('track', 'PageView');
  </script>
  <noscript><img height="1" width="1" style="display:none"
  src="https://www.facebook.com/tr?id=XXXXXXXXXXXXX&ev=PageView&noscript=1"
  /></noscript>
  <!-- End Facebook Pixel Code -->
  <script>
  </script>
</body>
</html>

这就是实现"的方式,但是它不起作用,至少是Facebook面板所说的.

That's how it was "implemented" but it doesn't work, at least is what the facebook panel says.

在使用Angular制作的SPA中执行此操作的正确方法是什么?

What's is the right way to do this in a SPA made with Angular?

推荐答案

我遇到了同样的问题,并提出了以下解决方案.仅适用于使用路由器的应用程序.希望对您有所帮助:

I had the same problem and I come up with the following solution. It will work only for apps using Router. Hope it helps:

  1. 在您的应用文件夹中,为像素服务创建一个文件夹(例如,facebook-pixel-service),然后为服务代码创建该文件(例如,facebook-pixel.service.ts),然后复制以下代码的工作方式如下:

  1. In your app folder create a folder for the pixel service (e.g. facebook-pixel-service), then create the file for the service code (e.g. facebook-pixel.service.ts) and copy the code bellow that works like following:

  • 应用程序第一次加载应用程序的根组件时,它将执行将facebook脚本附加到根组件html的操作.它还将调用init并为当前页面触发PageView事件(通常在Router上为路径"/").
  • 在应与应用程序的其他路径/页面相对应的所有其他执行上,它将仅触发PageView事件.

  • The first time the app loads the root component of your app it will execute attaching the facebook script to the root component html. It will also call init and fire a PageView event for the current page (typically it will be path "/" on Router).
  • On all other executions that should correspond to the other paths/pages of your app, it will just fire the PageView event.

import { Injectable } from '@angular/core';
@Injectable({
  providedIn: 'root'
})
export class FacebookPixelService {

  private loadOk:boolean = false;

  constructor() { }

  load() {
    if (!this.loadOk) {
      (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', '381817369337156');
      (window as any).fbq('track', 'PageView');
      this.loadOk = true;
      console.log('Facebook pixel init run!')
    }
    else {
      (window as any).fbq('track', 'PageView');
      console.log('Facebook PageView event fired!')
    }
  }
}

在服务的同一文件夹上,为提供程序创建另一个文件(例如facebook-pixel.provider.ts),该文件将在app.module上插入服务.下面的代码仅会创建一个提供程序,以在每次触发Router事件且此事件为NavigationEnd时订阅将调用我们的像素服务的事件,这意味着它是对路径/页面的成功更改.

On the same folder of the service create another file (e.g. facebook-pixel.provider.ts) for the provider that will inject the service on app.module. The code bellow will just create a provider that subscribe our pixel service to be called every time a Router event is fired and this event is a NavigationEnd which means it was a successful change on the path/page.

import { Provider, APP_BOOTSTRAP_LISTENER, ComponentRef } from '@angular/core';
import { Router, NavigationEnd } from '@angular/router';
import { FacebookPixelService } from './facebook-pixel.service'

export const FACEBOOK_PIXEL_PROVIDER: Provider = {
  provide: APP_BOOTSTRAP_LISTENER,
  multi: true,
  useFactory: FacebookPixelRouterInitializer,
  deps: [
    FacebookPixelService,
    Router
  ]
};

export function FacebookPixelRouterInitializer(
  $fpService: FacebookPixelService,
  $router: Router
) {
  return async (c: ComponentRef<any>) => {
    $router
      .events
      .subscribe(event => {
        if (event instanceof NavigationEnd) {
          console.log(`Navigated to URL: ${event.url}`);
          $fpService.load();
        }
      });
  };
}

  • 现在,只需在app.moudle文件的@NgModule指令上通知提供者.框架将完成其余工作,并确保它将订阅我们的提供程序到路由器,并在适当时调用它.以下代码段显示了如何通知提供商(搜索FACEBOOK_PIXEL_PROVIDER):

  • Now, just inform the provider on the @NgModule directive on the app.moudle file. The framework will do the rest and make sure it will subscribe our provider to the Router and call it when appropriate. The snippet below shows how to inform the provider (search for FACEBOOK_PIXEL_PROVIDER):

    ...
    import { RouterModule, Routes } from '@angular/router';
    ...
    import { AppComponent } from './app.component';
    ...
    import { FACEBOOK_PIXEL_PROVIDER } from './facebook-pixel-service/facebook-pixel.provider'
    
    @NgModule({
      declarations: [
        AppComponent,
        ...
      ],
      imports: [
        ...
        RouterModule.forRoot([
          { path: '', Component: TheRootPath},
          { path: 'path1', Component: Path1},
          { path: 'path2', Component: Path2},
          { path: '**', component: PageNotFoundComponent },
        ]),
      ],
      providers: [
        FACEBOOK_PIXEL_PROVIDER
      ],
      bootstrap: [AppComponent]
    })
    export class AppModule { }
    

  • 这篇关于如何在Angular中实现Facebook像素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆