首页 > 解决方案 > 将参数传递给路由,我是否正确检索数据?

问题描述

当我将数据(即 ID 号)传递给路由时,我会在 API 调用后从在本地存储此数据的单独服务中检索数据。这是[在Angular 8中]执行此操作的正确方法还是我遗漏了什么?

我在多个场合都有一个很好的谷歌,但似乎没有人直接回答这个问题,哈哈。

真的很抱歉,如果在某个地方有另一篇关于这个的帖子,不幸的是找不到最新版本的 Angular,但是对于旧版本来说很多。提前致谢,感谢所有帮助!

ngOnInit() {
  // subscribe to the parameters observable
  this.route.params.subscribe(params => {
     // let us assume params is '1' from a clicked component in a list
     // that routes to this component and passes just '1'.#
     // if I then use this to make a service call for my stuff, 
     // is this the correct way? i.e.,
     this.dummyStore = this.dummyService.getStuff(params);
  });
}

标签: angularangular-router

解决方案


您可以通过两种方式接收参数,对于路径变量,您可以使用以下示例

1.{路径:“水果/:水果”,组件:水果组件}

取回水果

constructor(private route: ActivatedRoute) { }

ngOnInit() {
 this.fruit = this.route.snapshot.paramMap.get("fruit")
}

2.for url查询参数

url = /param1=test&id=222&id2=99"


constructor(private route: ActivatedRoute) {
   this.route.queryParams.subscribe(params => {
    this.param1 = params['param1'];
});
}

推荐阅读