【问题标题】:How to allow certain URLs with angular and collect data from them如何允许某些带有角度的 URL 并从中收集数据
【发布时间】:2020-01-09 18:13:43
【问题描述】:

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

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

我非常感谢任何和所有的帮助。谢谢!

【问题讨论】:

标签: angular


【解决方案1】:

我建议创建一个新的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

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

【讨论】:

  • 哇!这正是我一直在寻找的。非常感谢,这非常有帮助!
  • 乐于助人! @RyanSoderberg
  • 由于某种原因,我得到 null 作为代码的值。你介意看看吗?由于字符限制,我将它们上传到这里repl.it/repls/HarshIllegalOs
【解决方案2】:

首先,您应该设置一个新的路由路径,更多的是 (here)。我会推荐类似的东西

{ path: 'r/:refId', component: ReferralComponent }

这还需要您创建一个referralComponent,您可以在其中处理id。如果我没记错的话,你可以在你的组件中使用路由器,你可以使用 router.url[0] 从 url 中获取参数。我可能误解了你的问题,如果是这样,请更具体一些,我会尽力提供更多帮助。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-12-25
    • 1970-01-01
    • 2018-05-02
    • 1970-01-01
    • 1970-01-01
    • 2013-04-01
    • 1970-01-01
    • 2021-04-08
    相关资源
    最近更新 更多