【问题标题】:Unable to access a route parameter through route.snapshot in root component无法通过根组件中的 route.snapshot 访问路由参数
【发布时间】:2018-11-15 13:41:29
【问题描述】:

我想从 url 获取令牌,但它返回 null 作为值。

app.component.ts:

import { Component, OnInit } from '@angular/core';
import { ActivatedRoute } from '@angular/router';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss']
})
export class AppComponent implements OnInit {    
  constructor(private route: ActivatedRoute) { }

    ngOnInit(){  
    const token = this.route.snapshot.paramMap.get('token');
    console.log(token);

和routing.ts

{ path: ':token', component: AppComponent }

我想在 / 之后抓取 url 中的内容,例如:localhost:4200/content-to-grab 有什么解决办法吗?

【问题讨论】:

  • 不鼓励使用快照。使用route.paramMap.subscribe 获取它们。
  • @trichetriche 你从哪里得到的?
  • @Jota.Toledo 我自己的理解和试验(可能还有一些我自己记不起的博客或文章):快照不会在相同的路线导航或 URL 参数更改时更新,而路线依赖 observables 并不断更新。
  • 所以?根据用例,访问snapshot 成员是完全有效的,因为ActivatedRouteSnapshot 的某些成员不会在导航事件上发生变化。例如,通过Route 定义的data 属性定义的静态值。
  • @Jota.Toledo,您可能想看看StackBlitz Sample 中的ngOnInit 中的代码。您会注意到使用snapshot 并不会提供更新后的id。此外,更重要的是使代码统一,以便开发人员一方面不会snapshot.params 而另一方面subscribeing 到route.params。大多数开发人员并不真正知道何时使用哪一个。我个人在 SO 上看到了很多关于相同问题的问题。

标签: angular angular-routing routeparams angular-activatedroute


【解决方案1】:

你的方法没问题,还有另一个概念问题:

您正在尝试将 路径 关联到 根组件

您的根模块很可能是这样的:

@NgModule({
  imports: [
    RouterModule.forRoot(...)
  ],
  declarations:[
    ...
    AppComponent,
    ...
  ],
  boostrap: [AppComponent]
})
export class AppModule {}

框架在引导步骤中实例化的AppComponent第一个实例将用作根组件,因此,注入的ActivatedRoute将与您的路线定义有点“脱节”。

此外,通过RouterOutlet 指令解析的AppComponent 实例将知道您的路由定义。

您可以在following stackblitz 中自行查看。

注入AppComponent 的第一个实例的ActivatedRoute 实例不会以异步或同步方式反映路由参数。 如果您导航到{url}/#/bla 之类的内容,由于<router-outlet>,将解析AppComponent 的第二个实例。注入其中的ActivatedRoute 实例将反映路由参数值,两者都是同步的。并且是异步的。

【讨论】:

  • 嗨@Jota.Toledo,抱歉回复晚了。实际上,我在这里询问后很快就想到了。无论如何感谢您的回答。!
【解决方案2】:

试着像这样抓住它。

this.route.snapshot.params["token"]

【讨论】:

    【解决方案3】:

    将您的代码更改为

    this.route.paramMap.subscribe(params => { console.log(params.get('token'));})
    

    【讨论】:

      【解决方案4】:
      ngOnInit(){  
          const token = this.activatedRout.snapshot.params.token;
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-06-29
        • 1970-01-01
        • 2020-05-19
        • 2019-07-22
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多