Angular5集成Angulartics2与Piwik后URL出现双#跟踪异常问题
我之前也碰到过这个问题,Angular 5默认的HashLocationStrategy和Angulartics2 Piwik的默认配置冲突,再加上手动添加的Piwik代码可能重复处理URL,就会出现你看到的双#问题。下面是具体的解决步骤:
1. 移除index.html中手动的URL跟踪代码
首先检查你的index.html里的Piwik嵌入代码,如果你加了类似下面的语句,一定要注释或删除:
// 把这两行删掉/注释掉 _paq.push(['setCustomUrl', window.location.href]); _paq.push(['trackPageView']);
原因很简单:Angulartics2已经会自动监听Angular的路由变化,自动推送正确的页面URL到Piwik。手动添加这两行会让Piwik同时收到手动拼接的完整URL和Angulartics2推送的路由URL,导致重复叠加#。
2. 配置Angulartics2适配Hash路由
在app.module.ts中,修改Angulartics2的初始化配置,明确开启相对路径跟踪,适配HashLocationStrategy:
import { NgModule } from '@angular/core'; import { Angulartics2Module, Angulartics2Piwik } from 'angulartics2'; @NgModule({ imports: [ // 添加上全局配置,开启trackRelativePath Angulartics2Module.forRoot([Angulartics2Piwik], { pageTracking: { trackRelativePath: true, clearIds: false } }) ] }) export class AppModule { }
trackRelativePath: true会让Angulartics2只推送Angular路由的相对路径(也就是#后面的部分),而不是整个window.location.href,从根源避免重复添加#。
3. 确保AppComponent中没有额外的URL处理
在app.component.ts里,只需要注入Angulartics2即可,不需要手动修改或推送URL:
import { Component } from '@angular/core'; import { Angulartics2 } from 'angulartics2'; @Component({ selector: 'app-root', templateUrl: './app.component.html' }) export class AppComponent { constructor(private angulartics2: Angulartics2) { // 这里不需要额外写任何跟踪代码,Angulartics2会自动监听路由 } }
4. 验证Piwik后台的网站配置
登录Piwik管理后台,找到你的网站设置,确保“网站URL”设置为http://localhost:4200/(不要带#或任何路由路径),这样Piwik在拼接完整URL时不会额外添加前缀。
做完这些步骤后,重新启动Angular应用,再操作路由,应该就能看到Piwik里跟踪的URL变成正常的http://localhost:4200/#/app/main-route/sub-route了。
内容的提问来源于stack exchange,提问作者Sampat

