0

I am making a simple Angular (version 4) application with TypeScript.

I have an URL that looks like this: www.example.com/api/1/countries/Italy/

And I want to get 1 and Italy from this URL and assign them to variables.

I tried with ActivatedRoute like this:

 ngOnInit() {
    this.router
        .queryParams
        .subscribe(params => {
           this.id = +params[''];
           this.country = +params[''];
        });
}

Where idand country are my private variables I want to assign with the values from the URL. But I don't know how exactly to proceed...

What else do I need to do?

2
  • 1
    Please look at solution in this post Commented Jun 1, 2017 at 15:50
  • 1
    1 and Italy aren't query parameters, they're route parameters. Commented Jun 1, 2017 at 15:52

2 Answers 2

1

In your URL example you don't use query parameters. So the code to get values from the ActivatedRoute could look like this:

 this.id = this.route.snapshot.paramMap.get('id');
 this.country = this.route.snapshot.paramMap.get('country');

This code assumes that you have configured your routes with params named id and country, e.g.

 {path: 'api/:id', component: CompA}
   ...
 {path: 'countries/:country', component: CompB}

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

2 Comments

Thanks! But if I have only one single Component. Does something like this make sense: {path: '/api/:id/countries/:country/', component: IndexPageComponent} ?
Yes, it'll work. you may not need the leading forward slash though.
0

you can access url using DOCUMENT and parse it.

component.ts

import { DOCUMENT } from '@angular/platform-browser';

  constructor(@Inject(DOCUMENT) document: any) {
    console.log(document.location.href);
  }

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.