typescript 在 Angular 6 服务中获取当前路由参数的最佳方法是什么?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/52205221/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-21 05:38:25  来源:igfitidea点击:

What is the best way to get current route params in Angular 6 services?

angulartypescriptangular-routing

提问by SMH

I am trying to find out what is the best way to get the current route params in Angular 6.

我试图找出在 Angular 6 中获取当前路由参数的最佳方法是什么。

At the moment I have to pass the ActivatedRouteto the service's method as argument and then use it in the service.

目前我必须将 传递ActivatedRoute给服务的方法作为参数,然后在服务中使用它。

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 {
            ...
        }
    }
}

回答by SiddAjmera

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.snapshot,您应该订阅activatedRoute.params。它将为您提供当前路由参数的最新和更新值。

Your service method should not be responsible for getting the idfrom the ActivatedRoute. It should be the responsibility of your Component. Your service should only be responsible for getting the idfrom the componentand then do the needful based on that id.

您的服务方法不应该负责idActivatedRoute. 这应该是你的责任Component。您的服务应该只负责id从 中获取component,然后在此基础上做必要的事情id

You should be extracting the id from the activatedRoutein your component. And then call the service method by passing it the id

您应该从activatedRoute组件中的中提取 id 。然后通过传递它来调用服务方法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));
            }
        })

    }
}

And in your service

并为您服务

@Injectable({
  providedIn: "root"
})
export class DataService {
    getChartsData(id) {
        if (id) {
            ...
        } else {
            ...
        }
    }
}

回答by Christoph Lütjen

In most cases services should not access routing. A "ChartDataService" should load and return charts that are identified by something (e.g. an id). Remember: If you access the current route directly in the service, you must never change the parameter name because this would break your data service.

在大多数情况下,服务不应访问路由。“ChartDataService”应加载并返回由某些内容(例如 id)标识的图表。请记住:如果您直接在服务中访问当前路由,则绝对不能更改参数名称,因为这会破坏您的数据服务。

export class ChartDataService {
  getChart(id: string) { … }
}

// in your component
const chartId = // read from activated route
this.chartsService.getChart(chartId);

If you really want to to access the current route in a service, you cannot inject ActivatedRoute (this is by design see e.g. https://github.com/angular/angular/issues/12884). But you can inject the Router itself and listen for navigation events:

如果您真的想访问服务中的当前路由,则不能注入 ActivatedRoute(这是设计使然,例如https://github.com/angular/angular/issues/12884)。但是你可以注入路由器本身并监听导航事件:

class MyClass {
  constructor(private router: Router) {
    router.events.subscribe((val) => {
        // see also 
        console.log(val instanceof NavigationEnd) 
    });
  }
}

Example from https://stackoverflow.com/a/33548895/2085502.

来自https://stackoverflow.com/a/33548895/2085502 的示例。

Docs: https://angular.io/guide/router#router-events

文档:https: //angular.io/guide/router#router-events