首页 > 解决方案 > 如何允许某些带有角度的 URL 并从中收集数据

问题描述

我正在尝试为我的 Angular 网站设置推荐系统。我的网站目前是可在 localhost:4200 访问的一个组件。我希望用户在访问网站时能够使用推荐代码,因此请考虑“localhost:4200/r/h7Gt4p”。

当有人导航到带有推荐标签的 URL 时,如何让我的角度页面加载主要组件中的内容。此外,我如何从我的打字稿文件中的 URL 中获取引用参数?

我真的很感激任何和所有的帮助。谢谢!

标签: angular

解决方案


我建议创建一个新ReferralComponent的如下:

@Component({
  selector: 'app-referral',
  templateUrl: './referral.component.html',
  styleUrls: ['./referral.component.css']
})
export class ReferralComponent implements OnInit {

  constructor(private route: ActivatedRoute, private router: Router) { }

  ngOnInit() {
    const code = this.route.snapshot.paramMap.get('code');
    // Process your code here. Then redirect
    this.router.navigate(['']);
  }
}

然后为您的应用配置路由:

const routes: Routes = [
  {
    path: 'r/:code',
    component: ReferralComponent
  },
  {
    path: '',
    redirectTo: 'home',
    pathMatch: 'full'
  },
  {
    path: 'home',
    component: HelloComponent
  }
]

在这里找到一个运行示例:https ://angular-app-initial-route.stackblitz.io/r/h7Gt4p

打开浏览器的控制台以查看捕获的代码。我希望它有帮助!


推荐阅读