132

I'm trying to get startdate from the URL. The URL looks like http://sitename/booking?startdate=28-08-2017

My code is below:

aap.module.ts

    import {...};

    @NgModule({
      declarations: [
        AppComponent, ModalComponent
      ],
      imports: [
        BrowserModule,
        FormsModule,
        HttpModule,
        JsonpModule,
        ReactiveFormsModule,
        RouterModule.forRoot([{
                path: '',
                component: AppComponent
            },
        ]),    
      ], 
      providers: [ContactService, AddonService, MainService],
      bootstrap: [AppComponent]
    })
    export class AppModule { }

aap.component.ts

import {...}
import {Router, ActivatedRoute, Params} from '@angular/router';

constructor(private activatedRoute: ActivatedRoute) {
  // subscribe to router event
  this.activatedRoute.queryParams.subscribe((params: Params) => {
    console.log(params);
  });

}

But its giving the below error

Unhandeled Promise rejection: No base href set. Please provide a value for the APP_BASE_HREF token or add a base element to the document. ; Zone: ; Task: Promise.then ; Value: Error: No base href set. Please provide a value for the APP_BASE_HREF token or add a base element to the document.

How does Angular know the base href?

Chris Stillwell
  • 10,266
  • 10
  • 67
  • 77
Sudha Bisht
  • 1,525
  • 3
  • 11
  • 12

13 Answers13

260

Routes

export const MyRoutes: Routes = [
    { path: '/items/:id', component: MyComponent }
]

Component

import { ActivatedRoute } from '@angular/router';
public id: string;

constructor(private route: ActivatedRoute) {}

ngOnInit() {
   this.id = this.route.snapshot.paramMap.get('id');
}
Chris Stillwell
  • 10,266
  • 10
  • 67
  • 77
Dmitry Grinko
  • 13,806
  • 14
  • 62
  • 86
  • 18
    This answer works better than the accepted one in my case. Thanks! – Ben Mar 09 '18 at 10:06
  • If i want to send one object and don't want to show that in url then what i can do ? – Anuj Mar 13 '18 at 12:18
  • @Anuj Use service – Dmitry Grinko Mar 13 '18 at 12:31
  • My Requirement is not like that , I want to click on one table and send that table data to other page which have 4-5 fields . – Anuj Mar 13 '18 at 12:41
  • 2
    @Anuj yes, you can use service for it. onClick(row: any) { this.shareService.setData(row); this.router.navigate(['/page2'])} and in your page2 you can get this data ngOnInit() { const data = this.shareService.getData(); } Hope it helps – Dmitry Grinko Mar 13 '18 at 13:00
  • Looking Great. Thanks for help , Actually i m new in angular 4 . One more qn is that how we will define that shareService. It is silly qn but currently i don't know flow of it bez i was working in ionic 2/3. – Anuj Mar 13 '18 at 13:41
  • @Anuj It is the same approach as ionic 2/3 – Dmitry Grinko Mar 13 '18 at 13:48
  • Which is best practice between `this.route.snapshot.paramMap.get('x')` and `this.route.snashop.params.x` ? – PierreD Jun 08 '19 at 12:28
  • really helpful .easy and exact solution than other –  Jul 30 '19 at 09:16
  • @Ben But if you want same page routing, you have to use the accepted answer. Let's say you are browsing through a list of detail pages that are accessed by an id from the url. in that case, you have to subscribe to the ActivatedRoute to detect the current id from the url. The snapshot is only for one time access. – Dejazmach Feb 29 '20 at 13:04
  • @Dejazmach This is a good answer about different between the Snapshot and Observable: https://stackoverflow.com/a/53242610/6108211 – Dmitry Grinko Mar 01 '20 at 20:27
  • @TobiasKaufmann https://stackoverflow.com/questions/47455734/how-to-get-query-parameters-from-url-in-angular-5 – Dmitry Grinko Sep 11 '20 at 15:26
  • 3
    It should be this._route.snapshot. **queryParamMap** .get, not paramMap! That got me stuck for a while. – Tony Sep 07 '22 at 12:48
  • 1
    @Tony The question was about Angular 4. If you have a solution for another Angular version feel free to add your answer, it will be helpful. – Dmitry Grinko Sep 09 '22 at 21:52
170

Update

I belive Dimitry Grinko's answer in this post is better than this one.

Old answer

This should do the trick retrieving the params from the url:

constructor(private activatedRoute: ActivatedRoute) {
  this.activatedRoute.queryParams.subscribe(params => {
        let date = params['startdate'];
        console.log(date); // Print the parameter to the console. 
    });
}

The local variable date should now contain the startdate parameter from the URL. The modules Router and Params can be removed (if not used somewhere else in the class).

Ørjan
  • 2,749
  • 2
  • 16
  • 24
  • this answer is work, but why after refreshing the page that have parameter on url will make the page become blank? – Fai Zal Dong Dec 14 '17 at 07:51
  • Hard to tell. The first thing that comes to my mind is that you maybe are navigating in the ngOnInit section of the typescript code without providing any parameters? Then it will naturally go back to the component without any params. – Ørjan Dec 14 '17 at 14:00
  • Hello @Curiosity_is_Learning I am trying to set the query params as a global variable. Currently with this logic "date" is only available within this subscribe method right? How to keep those query params value as a global variable. I tried let.date =['startdate'] but when calling it anywhere outside of the subscribe method, it is undefined. – JayC Aug 20 '20 at 18:53
  • hi @Jesse, this should be rather simple. Just declare a variable in the top of your Anulgar component like this: `private startDate: string;` then you should be able to replace the `let date = params['startdate'];` with `this.startDate = params['startdate'];`. Then you can reuse the variable elsewhere in the component as much as you like, simply by calling `this.startDate` – Ørjan Aug 22 '20 at 10:19
  • @Curiosity_is_Learning That is exactly what I did, but once I am calling "this.startDate" outside of the subscribe method. The value is undefined. Inside the subscribe method "this.startDate" prints out the proper date. – JayC Aug 24 '20 at 13:57
  • Hm... strange. Here is my working example I just made. Can you see any differences? The `clickTest` function is called from HTML code that i have not pasted here, and it is then logging to the console https://gist.github.com/ertkjern/1af7c3fc9d4a225159fd17c9f6cf655e – Ørjan Aug 24 '20 at 16:33
29

In angular, They separate it into 2 kind of url.

  1. URL pattern /heroes/:limit. Example: /heroes/20

    • You can get raw value by using route.snapshot.paramMap.get.
    • Subscribe from route.paramMap to get params
  2. URL pattern /heroes. Example: /heroes?limit=20

    • You can get raw value by using route.snapshot.queryParamMap

Reference: All you need to know about Angular parameters

Hoang Subin
  • 6,610
  • 6
  • 37
  • 56
26
constructor(private activatedRoute: ActivatedRoute) {
}

ngOnInit() {
    this.activatedRoute.params.subscribe(paramsId => {
        this.id = paramsId.id;
        console.log(this.id);
    });
  
 }
Teodor
  • 413
  • 6
  • 13
  • 4
    This is the best answer in my opinion for angular 5. Thank you! – Combine May 23 '18 at 12:04
  • 1
    Can't observable be resolved on next eventloop frame with undefined in console? – vp_arth Aug 13 '19 at 09:01
  • This gives me "undefined" – Sarah Jul 05 '20 at 16:33
  • This also gives me "undefined". For some reason, I am suspecting that this issue is happening on "ngOnInit". When I created another method and performed (console.log(this.id) I am able to see the proper data. But having console.log exactly where you have it in your answer; I received an undefined in the console. – JayC Aug 24 '20 at 14:17
  • I edited this, my bad :D it was giving you undefined because at the moment the console log happened the data from subscribe was not received. (Don't do it like that :D, I was a beginner at that time), to test the value, try to put it in the same function scope. – Teodor Jan 08 '21 at 21:29
12

app.module.ts

import { Routes,RouterModule } from '@angular/router';

const routes: Routes = [
    { 
       path: '', 
       component: HomeComponent 
    }
    { 
       path: '/users/:id/:name', 
       component: UsersComponent 
    }
]

@NgModule({
   ....
   imports : [
       .......,
       RouterModule.appRoot(routes)
   ]
   ....
})

Component Page

import { ActivatedRoute, Params } from '@angular/router';

export class UserComponent implements OnInit {
    user : {id: number, name: string};

    constructor(private route: ActivatedRoute) {}

    ngOnInit() {
        // If you get param one time in page use below code...
        this.user = {
            id : this.route.snapshot.params['id'],
            name : this.route.snapshot.params['name']   
        };
        // Dynamically change params use below code...
        this.route.params.subscribe((param : Params) => {
            this.user.id = param['id'];
            this.user.name = param['name'];
        });
    }
}
AngularJMK
  • 1,178
  • 13
  • 15
  • Thanks for your answer. This one worked for me in 2022 with Angular 14. Not the accepted answer, I guess something has changed in Angular API: https://stackoverflow.com/a/45998138/8784518 – Kasir Barati Jun 22 '22 at 09:12
  • This answer works for me with Angular: 15.2.3 – neelmeg Mar 28 '23 at 06:37
8

The accepted answer uses the observable to retrieve the parameter which can be useful in the parameter will change throughtout the component lifecycle.

If the parameter will not change, one can consider using the params object on the snapshot of the router url.

snapshot.params returns all the parameters in the URL in an object.

constructor(private route: ActivateRoute){}

ngOnInit() {
   const allParams = this.route.snapshot.params // allParams is an object
   const param1 = allParams.param1 // retrieve the parameter "param1"
}
edkeveked
  • 17,989
  • 10
  • 55
  • 93
7

Check parameters from URL string or as :param in your routeConfig

downstream.component.ts

...
import {Router,ActivatedRoute} from '@angular/router';
...    
export class DownstreamComponent  {
    constructor(
    private route: ActivatedRoute,
    private router: Router
) {
    if(this.route.snapshot.queryParams) 
      console.log(this.route.snapshot.params); // e.g. :param1 in routeConfig
    if(this.route.snapshot.queryParamMap.get('param1'))
      console.log(this.route.snapshot.queryParamMap.get('param1')); // e.g. in URI ?param1=blah
}

}
Chris Stillwell
  • 10,266
  • 10
  • 67
  • 77
Hunter Frazier
  • 487
  • 5
  • 9
4

You can try this:

this.activatedRoute.paramMap.subscribe(x => {
    let id = x.get('id');
    console.log(id);  
});
Chris Stillwell
  • 10,266
  • 10
  • 67
  • 77
BorisD
  • 1,611
  • 17
  • 22
3
import {Router, ActivatedRoute, Params} from '@angular/router';

constructor(private activatedRoute: ActivatedRoute) { }

  ngOnInit() {
    this.activatedRoute.paramMap
    .subscribe( params => {
    let id = +params.get('id');
    console.log('id' + id);
    console.log(params);


id12
ParamsAsMap {params: {…}}
keys: Array(1)
0: "id"
length: 1
__proto__: Array(0)
params:
id: "12"
__proto__: Object
__proto__: Object
        }
        )

      }
Chris Stillwell
  • 10,266
  • 10
  • 67
  • 77
ganesh
  • 41
  • 4
3

try this one. if your URL param is like http://127.0.0.1:8000/profile/?startdate=12-02-2022

const date = this.ActivatedRoute.snapshot.queryParamMap.get('startdate'); 
console.warn(date)
2

use paramMap

This will provide param names and their values

//http://localhost:4200/categories/1
//{ path: 'categories/:category', component: CategoryComponent },

import { ActivatedRoute } from '@angular/router';

constructor(private route: ActivatedRoute) { }

ngOnInit() {

  this.route.paramMap.subscribe(params => {
        console.log(params)
  })
}
Chris Stillwell
  • 10,266
  • 10
  • 67
  • 77
WasiF
  • 26,101
  • 16
  • 120
  • 128
0

Hope this helps someone. In case that u get undefined while doing this with something that's not "id", check if u are passing right parameter:

If your route in parent-component.ts is:

 onSelect(elem) {
    this.router.navigateByUrl(`/element/${elem.type}`);
  }

And in child-component.ts

  type: string;
  elem: ElemModel;

  constructor(
    private elemService: ElemService,
    private route: ActivatedRoute
  ) {}

  ngOnInit() {
    this.route.params.subscribe((data) => {

      console.log(data);  // 'data' will give u an object with the type inside, check the 
      name of that type inside console of devTool, as u will put that name inside 
      data[HERE] down below.

      this.type = data["elem-type-maybe"]; // Don't do this.type = data["type"], do 
      data[NAME] as said above.

      this.elem = this.elemService.getElem(this.type); // getElem is method in service 
      which returns that specific type.
    });
0

Please try this for get startdate from given your booking URL route parameter:

import { Component, OnInit } from '@angular/core';
import { ActivatedRoute } from '@angular/router';

@Component({
  selector: 'app-hero',
  templateUrl: './hero.component.html',
  styleUrls: ['./hero.component.css']
})
export class HeroComponent implements OnInit {

  constructor(private activeRoute: ActivatedRoute) { 
    this.activeRoute.queryParams.subscribe((qp) => {
      console.log('Get Router Params:', this.activeRoute.snapshot.queryParams.startdate);
    });
  }

  ngOnInit(): void {
  }

}

For route URL related more information you can go through here

KK Nebula
  • 121
  • 1
  • 2