angular引入外部库_Angular:添加Google Analytics(分析)(外部脚本)

诸葛彦
2023-12-01

angular引入外部库

Google Analytics is a fantastic resource when attempting to capture basic visitor behavior in your Angular application. To utilize Google Analytics, you will need to add the tracking script to your application’s source. Angular provides a few different mechanisms to accomplish this. The first approach it to save the tracking script to an external JavaScript file and include the file into your bundle for production releases. This approach is what the following blog post attempts to demonstrate.

尝试捕获Angular应用程序中的基本访问者行为时,Google Analytics(分析)是一种绝佳的资源。 要使用Google Analytics(分析),您需要将跟踪脚本添加到应用程序的源中。 Angular提供了几种不同的机制来完成此任务。 第一种方法是将跟踪脚本保存到外部JavaScript文件,并将该文件包含在捆绑包中以进行生产发行。 以下博客文章试图演示这种方法。

As stated, there are a few approaches to including the Google Analytics code in your Angular application. This post will focus on levering a plain, external JavaScript file. The next post demonstrates how to include Google Analytics as an Angular service. All source code for this post can be found in my demo GitHub repository. Finally, this post assumes you understand how to use the Angular CLI.

如前所述,有几种方法可以将Angular应用程序中包含Google Analytics(分析)代码。 这篇文章将重点介绍如何利用一个简单的外部JavaScript文件。 下一篇文章演示了如何将Google Analytics(分析)作为Angular服务。 这篇文章的所有源代码都可以在我的演示GitHub存储库中找到 。 最后,本文假定您了解如何使用Angular CLI

建立 (Setup)

Let’s begin by creating a few things:

让我们开始创建一些东西:

  1. A new Angular application.

    一个新的Angular应用程序。

    The demo application is using CLI version 8.3.29, but you can use whichever version you prefer. I’ve also chosen to use SCSS for my styles, but, again, choose what you prefer. Finally, make sure you

    该演示应用程序使用的是CLI版本8.3.29,但是您可以使用自己喜欢的任何版本。 我还选择将SCSS用于我的样式,但是,再次选择您喜欢的样式。 最后,请确保您

    enable routing. Enabling routing will help with requests and can be utilized for things like setting the page titles through routing properties.

    启用路由 。 启用路由将有助于请求,并可用于诸如通过路由属性设置页面标题之类的事情。

  2. Create a few pages.

    创建几页。

    For the demo application, I’ve created 3 pages — Home, First Page, and Second Page. Additionally, on my first and second pages, I’ve added some buttons that bind to click events. This will allow us to interact with Google Analytics’s API for tracking customer interactions.

    对于演示应用程序,我创建了3页-主页,第一页和第二页。 此外,在第一页和第二页上,我添加了一些绑定到单击事件的按钮。 这将使我们能够与Google Analytics(分析)的API进行交互,以跟踪客户的交互。

  3. Create a Google Analytics account along with a site.

    创建一个Google Analytics(分析)帐户以及一个网站。

谷歌分析 (Google Analytics)

When creating a Google Analytics account, you will be presented with two options (formats) for the tracking code — the legacy format (using the ga method) and the newer format (gtag). Examples of each are below. (NOTE: The UA-XXXXXXXXX-1 code below will be different for your site. I've kept my demo code in the source for your reference.) In my repository, I've included both formats, but have commented out the legacy and the original, new format (see below for modifications).

创建Google Analytics(分析)帐户时,系统会为您提供跟踪代码的两个选项(格式)-旧格式(使用ga方法)和较新的格式( gtag )。 每个示例如下。 ( 注意:下面的UA-XXXXXXXXX-1代码因您的站点而异。我已将演示代码保留在源代码中,以供您参考。)在我的存储库中,我包括了这两种格式,但已注释掉了旧格式和原始的新格式(有关修改,请参见下文)。

Legacy Format:

旧版格式:

New Format:

新格式:

Whichever format you choose is entirely your decision. For a site that is being migrated or upgraded and already have Google Analytics enabled, you’ll need to confirm which format it’s currently using (NOTE: It appears that the ga method works with the newer format too, but I cannot guarantee complete compatibility nor any point(s) of deprecation).

选择哪种格式完全由您决定。 对于正在迁移或升级且已启用Google Analytics(分析)的网站,您需要确认其当前使用的格式( 注意: ga方法似乎也适用于较新的格式,但我不能保证完全兼容,也不能保证折旧的任何点)。

保存跟踪代码 (Saving the Tracking Code)

Once you’ve copied the code of your choice, you will need to save that code to a file for bundle injection.

复制您选择的代码后,您需要将该代码保存到文件中以进行捆绑注入。

Within the default Angular folder structure, there exists the folder src/assets. Create a new folder inside assets called scripts, and create a new file called google-analytics.js. (HINT: The new folder structure should appear as src/assets/scripts/google-analytics.js.) Paste your copied tracking code into this file and save it.

在默认的Angular文件夹结构中,存在src/assets文件夹。 在assets内创建一个名为scripts的新文件夹,并创建一个名为google-analytics.js的新文件。 ( 提示:新的文件夹结构应显示为src/assets/scripts/google-analytics.js 。)将复制的跟踪代码粘贴到此文件中并保存。

JavaScript修改 (JavaScript Modification)

Because the legacy format uses “pure” JavaScript, it can be copied and pasted as-is. Unfortunately, the new format will require a few changes so that it can be “injected” properly by the Angular application after bundling.

由于旧格式使用“纯” JavaScript,因此可以按原样复制和粘贴。 不幸的是,新格式将需要进行一些更改,以便在捆绑后可以由Angular应用程序正确“注入”。

The modification will utilize JavaScript Promises for 1) creating the JavaScript script element; and, 2) adding the gtag method calls. Comparing to the original code above, see the necessary modifications below.

修改将利用JavaScript Promises进行以下操作:1)创建JavaScript script元素; 并且,2)添加gtag方法调用。 与上面的原始代码相比,请参见下面的必要修改。

Because we aren’t adding the JavaScript to our application’s index.html and, instead, bundling it, we must wait for the Angular application to build and render the page. Once the page has rendered, the two JavaScript Promises will execute. The first Promise appends the Google Tag Manager script to the page's body element, and then loads it asynchronously. Once complete, the Promise resolves and calls the gtag method. The second gtag method (highlighted) is what registers a page view with Google Analytics.

因为我们没有将JavaScript添加到应用程序的index.html ,而是将其捆绑在一起,所以我们必须等待Angular应用程序生成并呈现页面。 页面呈现后,将执行两个JavaScript Promises。 第一个Promise将Google跟踪代码管理器脚本附加到页面的body元素,然后异步加载。 完成后,Promise会解析并调用gtag方法。 第二个gtag方法(突出显示)是向Google Analytics(分析)注册页面视图的方法。

包括捆绑 (Including with the Bundle)

There’s one last step to adding the JavaScript code to your application and that’s telling the CLI (WebPack) to package the analytics code with the compiled bundles.

将JavaScript代码添加到应用程序的最后一步是告诉CLI(WebPack)将分析代码与已编译的软件包打包在一起。

One thing to note, we don’t want to track page views while the application is under development (local developer machines, shared development/QA environments, UAT, etc.). We only want to track page views when the application is pushed to production. The Angular CLI configuration file allows us to accomplish this very easily.

需要注意的一件事是,我们不希望在开发应用程序时(本地开发人员机器,共享的开发/ QA环境,UAT等)跟踪页面浏览量。 我们只想在应用程序投入生产时跟踪页面浏览量。 Angular CLI配置文件使我们可以非常轻松地完成此操作。

In the application’s top folder, locate the angular.json file and open it. On line (approximately) 36, you'll see the JSON node "production". At the end of this node, you will see a "scripts" node defining an array. (NOTE: Your array may be empty or contain elements depending on whether you are working with a new application or an application already under active development.) Add your Google Analytics script file's path (e.g. "src/assets/scripts/google-analytics.js") to the array. You can refer to the demo in GitHub for assistance.

在应用程序的顶部文件夹中,找到angular.json文件并打开它。 在第36行(大约)上,您将看到JSON节点"production" 。 在该节点的末尾,您将看到一个定义数组的"scripts"节点。 ( 注意:您的数组可能为空,或者包含元素,具体取决于您是在使用新应用程序还是正在开发中的应用程序。)添加Google Analytics(分析)脚本文件的路径(例如"src/assets/scripts/google-analytics.js" )到数组。 您可以参考 GitHub中的演示以获得帮助。

测试 (Test)

At this point, your application should be ready for testing page views.

此时,您的应用程序应已准备好测试页面视图。

While under development, you are typically viewing/testing application changes by executing the command ng serve. However, remember, the Google Analytics code is only included when you specify the production build configuration. Therefore, to test the Google Analytics in your development environment, you will need to include the --prod flag (e.g. ng serve --prod).

在开发过程中,您通常通过执行命令ng serve查看/测试应用程序更改。 但是,请记住,仅当您指定生产构建配置时才包含Google Analytics(分析)代码。 因此, 要在您的开发环境中测试Google Analytics(分析),您需要包括 --prod 标志 (例如ng serve --prod )。

Once the application is running (with the production configuration loaded), begin navigating throughout your pages while checking your Google Analytics dashboard. You should see that you have one (or two) realtime visitor(s).

应用程序运行(加载了生产配置)后,开始浏览整个页面,同时检查Google Analytics(分析)信息中心。 您应该看到您有一个(或两个)实时访问者。

Now that Google Analytics has successfully been added to the application, you may want to track some basic user interactions. Continue on to learn how.

现在,Google Analytics(分析)已成功添加到应用程序中,您可能希望跟踪一些基本的用户交互。 继续学习。

捕捉互动 (Capturing Interaction)

Google Analytics was designed to provide insights on user experience based on user interactions. It is not so much an Application Performance Monitor (APM) like Application Insights or New Relic (while it can provide some extremely basic insights), but rather to assist internal teams with increasing conversion rates and improving customer acquisition (and retention). To this end, we may want to add some basic interactions to our Google Analytics metrics. In this post, we’re not going to cover goal setting, funnels, metrics, etc. We’re simply going to track a few events. However, the following principles can be used to accomplish the same purpose.

Google Analytics(分析)旨在根据用户互动提供有关用户体验的见解。 它不只是像Application Insights或New Relic这样的Application Performance Monitor(APM)(尽管它可以提供一些非常基础的见解),而是帮助内部团队提高转换率并改善客户获取(和保留)。 为此,我们可能想向我们的Google Analytics(分析)指标添加一些基本的交互。 在本文中,我们将不讨论目标设定,渠道,指标等。我们仅跟踪一些事件。 但是,以下原理可用于实现相同的目的。

创建一个按钮 (Create a Button)

On my application’s First Page (that I created in my “Setup” on page 1 of this post). I’ve created a simple button, and I bound it to a click event.

在应用程序的首页上 (我在本文第1页的“设置”中创建的页面)上。 我创建了一个简单的按钮,并将其绑定到click事件。

<button (click)="click()">Click Me!</button>

View the source here.

此处查看源代码。

In my page’s TypeScript file, I’ve created a click function. Depending on whether you are using the legacy analytics code or the new code, your method will call a different Google Analytics function.

在页面的TypeScript文件中,我创建了一个click函数。 根据您使用的是旧版分析代码还是新代码,您的方法将调用其他Google Analytics(分析)函数。

Legacy Format:

旧版格式:

New Format:

新格式:

You can find the source here.

您可以在此处找到源。

Essentially, both code samples accomplish the same thing; namely, they register an event with Google Analytics. The only call-out here is line 3 (for both versions). In each version, depending on which library we are using, we declare a variable (e.g. ga or gtag) outside the scope of the component. This is to prevent compilation errors from the TypeScript compiler.

本质上,这两个代码示例都完成相同的事情。 也就是说,他们在Google Analytics(分析)中注册了一个活动。 这里唯一的标注是第3行(两个版本)。 在每个版本中,根据我们使用的是哪个库,我们在组件范围之外声明一个变量(例如gagtag )。 这是为了防止来自TypeScript编译器的编译错误。

(NOTE: One downside of using Google Analytics is that the values for a specific event are summed in the daily reports. So, if the button on the page is clicked 3 times, the final event report will show 6 (1 for the first click + 2 for the second + 3 for the third) for the value. If you want to track values for individual users, sessions, clicks, etc., then you’ll need to configure metrics in Google Analytics.)

( 注意:使用Google Analytics(分析)的一个缺点是特定事件的值会在每日报告中汇总 。因此,如果单击页面上的按钮3次,则最终事件报告将显示6(第一次点击为1 + 2代表第二个+ 3代表第3个)的值。如果您要跟踪单个用户,会话,点击次数等的值,则需要在Google Analytics(分析)中配置指标。)

With your click event wired up, go ahead and run your application again (remember, with the --prod flag). You’ll then begin to see events being logged in realtime on your Google Analytics dashboard.

连接好click事件后,继续并再次运行您的应用程序(请记住,带有--prod标志)。 然后,您将开始在Google Analytics(分析)仪表板上看到实时记录的事件。

结论 (Conclusion)

We’ve just added Google Analytics to our Angular application by utilizing an external JavaScript file. There is a better, “more Angular” way to do this via services (which we’ll cover in the next post). However, this approach is great for the quick, simple addition of Google Analytics to a new project, or to add Google Analytics to a pre-existing project where the return on injecting Google Analytics as a service isn’t really worth the investment of time.

我们刚刚通过使用外部JavaScript文件将Google Analytics(分析)添加到了Angular应用程序中。 有一种更好的,“更多角度的”方式可以通过服务来做到这一点(我们将在下一篇文章中介绍 )。 但是,这种方法非常适合快速,简单地将Google Analytics(分析)添加到新项目中,或者将Google Analytics(分析)添加到先前存在的项目中,在这种情况下,将Google Analytics(分析)作为服务注入的回报并不值得花费时间。

Personally, I only use Google Analytics for tracking page views. That’s it. For other metrics, such as application performance and user interaction, I use a formal APM (such as Application Insights or New Relic).

就个人而言,我使用Google Analytics(分析)来跟踪页面浏览量。 而已。 对于其他指标,例如应用程序性能和用户交互,我使用正式的APM(例如Application Insights或New Relic)。

Again, for the full source code to this project, check out my GitHub blog demos repository.

再次,有关此项目的完整源代码,请查看我的GitHub blog demos存储库

Originally published at http://jdav.is on July 27, 2020.

最初于 2020年7月27日 http://jdav.is 发布

翻译自: https://medium.com/@jdav.is/angular-adding-google-analytics-external-script-joshua-davis-327ce1176b40

angular引入外部库

 类似资料: