0

I'm trying to create a service in angular 5, which will query the URL parameters, extract required parameters and assign it to specific type of interface which I created. I tried this, but it is not working:

export class UrlQueryService {

  urlParams = {} as UrlQueryParams;

  constructor( private router: Router, private route: ActivatedRoute) {

  }

  getParams() {
    this.route.queryParams.
    subscribe(
      (params: Params) => {
        this.urlParams.id = params['id'];
        this.urlParams.name = params['name']

      }

    )

    return this.urlParams;
  }

}

I wanted my service return parameters, but when I cal this service in my component I'm getting 'id' and 'name' undefined

2 Answers 2

1

Try this:

export class UrlQueryService {

  urlParams = {} as UrlQueryParams;

  constructor( private router: Router, private route: ActivatedRoute) {

//subscribe in constructor / onInit
    this.route.queryParams.
    subscribe(
      (params: Params) => {
        this.urlParams.id = params['id'];
        this.urlParams.name = params['name']

      }

    )

//
  }

  getParams() {
    return this.urlParams;
  }

}

One time subscribe is enough. when you keep subscribing each time you call the method you will face troubles.

Note: This example works for this situation: URL = "http://someting.com/?param1=ex1&param2=123

In the Heroes example, the params look like this: "http://something.com/param1/param2 In this situation you get the params by this code:

    this.urlParams.id = this.route.snapshot.params.id;
    this.urlParams.name = this.route.snapshot.params.name;

Sign up to request clarification or add additional context in comments.

Comments

0

The angular router sends the parameters to target component, and only it will be able to read those parameters. I also had a similar problem, and it seems that the router shares the params only with the target component, not with service.

However, you can use router events in service like RoutesRecognized to access the url parameters.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.