在 Angular 6 服务中获取当前路由参数的最佳方法是什么? [英] What is the best way to get current route params in Angular 6 services?
问题描述
我正在尝试找出在 Angular 6 中获取当前路由参数的最佳方法.
I am trying to find out what is the best way to get the current route params in Angular 6.
目前我必须将 ActivatedRoute
作为参数传递给服务的方法,然后在服务中使用它.
At the moment I have to pass the ActivatedRoute
to the service's method as argument and then use it in the service.
export class MainComponent {
constructor(private dataService: DataService, private activeRoute: ActivatedRoute) { }
getChartsData() {
return this.dataService(this.activeRoute);
}
}
@Injectable({
providedIn: "root"
})
export class DataService {
getChartsData(activatedRoute) {
if (activatedRoute.snapshot.params['id']) {
...
} else {
...
}
}
}
推荐答案
既然你想要当前的路由参数,而不是 activatedRoute.snapshot
,你应该订阅 activatedRoute.params代码>.它将为您提供当前路由参数的最新和更新值.
Since you want the current route params, instead of activatedRoute.snapshot
, you should be subscribing to activatedRoute.params
. It will give you the latest and updated value of the current route params.
您的服务方法不应该负责从 ActivatedRoute
获取 id
.这应该是你的 Component
的责任.您的服务应该只负责从 component
获取 id
,然后根据该 id
做必要的事情.
Your service method should not be responsible for getting the id
from the ActivatedRoute
. It should be the responsibility of your Component
. Your service should only be responsible for getting the id
from the component
and then do the needful based on that id
.
您应该从组件中的 activatedRoute
中提取 id.然后通过将 id
You should be extracting the id from the activatedRoute
in your component. And then call the service method by passing it the id
export class MainComponent {
constructor(
private dataService: DataService,
private activeRoute: ActivatedRoute
) { }
getChartsData() {
this.activeRoute.params.subscribe(params => {
if(params['id']) {
this.dataService.getChartsData(params['id'])
.subscribe(data => console.log(data));
}
})
}
}
并为您服务
@Injectable({
providedIn: "root"
})
export class DataService {
getChartsData(id) {
if (id) {
...
} else {
...
}
}
}
这篇关于在 Angular 6 服务中获取当前路由参数的最佳方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!