M
M
MOTORIST2017-09-16 10:59:35
Angular
MOTORIST, 2017-09-16 10:59:35

How to get a dynamic route parameter in a service?

Angular 2
You can receive in a component and pass it to service methods, which is not very convenient.
In the component:

create() {
   this.route.paramMap.subscribe((params) => {
       this.service.cerate(params.get('id'));
   });
}

update() {
   this.route.paramMap.subscribe((params) => {
       this.service.update(params.get('id'));
   });
}

You can create a provider that will create a service instance with a parameter in the component. Then it will not be necessary to prescribe it in each function.
In the component:
service: any;
  ngOnInit(): void {
     this.route.paramMap.subscribe((params) => {
          this.service = this.seviceProvider.factory(params.get('id'));
     }
  }

create() {
     this.service.cerate();
}

Maybe there is a more elegant solution?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
O
ozknemoy, 2017-09-16
@ozknemoy

in any case, it will be necessary to subscribe to the dynamics and the code will not become more beautiful / smaller. but for statics, you can simply this.route.snapshot.queryParams['id'];

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question