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?

lapadets
  • 1,067
  • 10
  • 38

2 Answers2

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}

Yakov Fain
  • 11,972
  • 5
  • 33
  • 38
  • Thanks! But if I have only one single Component. Does something like this make sense: `{path: '/api/:id/countries/:country/', component: IndexPageComponent}` ? – lapadets Jun 01 '17 at 16:03
  • 1
    Yes, it'll work. you may not need the leading forward slash though. – Yakov Fain Jun 01 '17 at 16:08
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);
  }
CharanRoot
  • 6,181
  • 2
  • 27
  • 45