【问题标题】:Problem in fetching route parameters using route.snapshot使用 route.snapshot 获取路由参数时出现问题
【发布时间】:2019-03-24 04:58:24
【问题描述】:

我有一条带有动态路径段的路线

const route:Routes=[
{path:'customers',component:CustomerComponent}
{path:'customers/:id',component:CustomerComponent}
]

所以在我的客户组件中,我使用 身份证号码;

constructor(private route:ActivatedRoute){}

ngOnInit(){

this.id= this.route.snapshot.params['id'];

console.log("Id is :",this.id)
}

当我从另一个组件转到此路由路径时控制台日志“Id 为:1”或第一次转到此路由时它正常工作“localhost:4200/customers/1”但问题发生了。我写了一个链接 customer.html 文件

<a [routerLink]="['/customer',2]">loadID2</a>

当单击此链接时,URL 更改为“localhost:4200/customers/2”,但控制台日志不起作用,它没有显示“Id is :2”,没有控制台日志。 我的问题为什么会发生这种情况?,网址已经更改,但 ngOninit 无法正常工作。你能帮我解决这个问题吗

【问题讨论】:

标签: angular


【解决方案1】:

不要使用ActivatedRoute.snapshot 来获取路由参数,而是订阅ActivatedRoute.paramMap Observable 以获取新的id

this.route.paramMap.subscribe((params : ParamMap)=> {  
      this.id = +params.get('id');
      console.log("Id is :", this.id);        
}); 

【讨论】:

  • 应该是params=>{this.id=+params.get('id'); });因为 id 是 number ,但是 console.log("Id is :", this.id);仍然无法正常工作,但是当将“id”绑定到

    id is : {{id}}

    时,它正在正确更改。我的问题是为什么控制台日志不起作用,当路由相同或它们中发生的事情时,角度是否不运行 ngOnint。
  • 我认为您正在尝试在 subscribe 呼叫之外使用 console.log。由于 paramMap 是一个 Observable,您只会在 subscribe 回调中看到更改后的值。在subscribe 回调中,您实际上是在实现一个Observer,它在收到新值时调用其next 方法。因此,如果您将 console.log 放入 ngOnInit 而不是放入 subscribe 调用中,您将不会看到更改后的新值。
  • 是的,你是对的,我们必须把它放在订阅中。但是我有疑问,为什么当我们更改路由路径时 angular ngOnint 没有运行,现在我的代码可以正常工作了。
  • ngOnInit 只被调用一次,当组件第一次经历变化检测时,所以你只会看到console.log 输出一次。但是如果你在订阅调用中添加一个console.log,当观察者接收到下一个元素时,你实现的next方法将被调用并且你的console.log将被调用(正如你在subscribe回调中next方法的实现)。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-09-16
  • 2017-12-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-01-07
相关资源
最近更新 更多