Sudha Bisht
Sudha Bisht

Reputation: 1615

How to get param from url in angular 4?

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?

Upvotes: 141

Views: 391050

Answers (13)

Pankaj Sajekar
Pankaj Sajekar

Reputation: 78

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)

Upvotes: 3

AngularJMK
AngularJMK

Reputation: 1268

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'];
        });
    }
}

Upvotes: 14

Ørjan
Ørjan

Reputation: 2879

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).

Upvotes: 176

KK Nebula
KK Nebula

Reputation: 129

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

Upvotes: 0

Boban BoBo Banjevic
Boban BoBo Banjevic

Reputation: 63

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.
    });

Upvotes: 0

Teodor
Teodor

Reputation: 413

constructor(private activatedRoute: ActivatedRoute) {
}

ngOnInit() {
    this.activatedRoute.params.subscribe(paramsId => {
        this.id = paramsId.id;
        console.log(this.id);
    });
  
 }

Upvotes: 26

Hoang Subin
Hoang Subin

Reputation: 7460

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

Upvotes: 34

BorisD
BorisD

Reputation: 1824

You can try this:

this.activatedRoute.paramMap.subscribe(x => {
    let id = x.get('id');
    console.log(id);  
});

Upvotes: 4

Hunter Frazier
Hunter Frazier

Reputation: 477

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
}

}

Upvotes: 7

ganesh
ganesh

Reputation: 41

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
        }
        )

      }

Upvotes: 3

WasiF
WasiF

Reputation: 28939

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)
  })
}

Upvotes: 2

Dmitry Grinko
Dmitry Grinko

Reputation: 15212

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');
}

Upvotes: 276

edkeveked
edkeveked

Reputation: 18401

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"
}

Upvotes: 8

Related Questions