在Angular 6服务中获取当前路线参数的最佳方法是什么? [英] What is the best way to get current route params in Angular 6 services?

查看:54
本文介绍了在Angular 6服务中获取当前路线参数的最佳方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试找出在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.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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆