How to get params from the url with aurelia
Asked Answered
O

5

7

For example: http://localhost:3000/#/report/123456

How do I get the "123456" part from the url with Aurelia?

Hope you can help me, couldn't find anything useful in the docs.

Ovarian answered 22/4, 2016 at 7:46 Comment(0)
T
13

you can get the submitted params in the activate method of the router (in your viewmodel)

activate(params) {
   return this.http.fetch('contacts/' + params.id)
      .then(response => response.json())
      .then(contact => this.contact = contact);
}

found in a nice blogpost here: http://www.elanderson.net/2015/10/aurelia-routing-with-a-parameter/

Tafoya answered 22/4, 2016 at 8:16 Comment(3)
I think you might be missing out adding a route for this { route: ['report/:id'], moduleId: './report', title: 'Report', name: 'report' },Tildatilde
Here is the relevant docs link that talks about params: aurelia.io/docs.html#/aurelia/framework/1.0.0-beta.1.2.2/doc/…Nader
@JohnManko: that link no longer works, it is now aurelia.io/hub.html#/doc/article/aurelia/framework/latest/…Nonbeliever
C
6

You have to have a route defined for it:

{ 
    route: ['report/:id'], 
    moduleId: './report', 
    title: 'Report', 
    name: 'report' 
}

Then in your view model, you can get the id from the params object:

activate(params) {  
    console.log(params.id);
}
Cheeks answered 8/5, 2017 at 21:36 Comment(0)
R
4

Get the router in the constructor via Dependency Injection and you can use it's values:

import { autoinject } from 'aurelia-framework';
import { Router } from 'aurelia-router';

@autoinject()
export class SomeClass {
  
  constructor(private router : Router) { }

  attached() {
    console.log(this.router.currentInstruction.params.myParam);
  }
}

The query string params are also available: e.g.: http://localhost:3000/#/report?id=123456

this.router.currentInstruction.queryParams.id  // "123456"
Robedechambre answered 24/4, 2017 at 8:27 Comment(0)
P
3

Adding to Mike's answer (unfortunately I don't have enough credits yet to comment): In case you want your parameter to be optional, you can just add a question mark after the parameter:

{ 
    route: ['report/:id?'], 
    moduleId: './report', 
    title: 'Report', 
    name: 'report' 
}
Ploce answered 23/9, 2019 at 15:4 Comment(0)
E
-8
var str = "http://localhost:3000/#/report/123456";
var res = str.split("/");
document.getElementById("demo").innerHTML = res[5];
Engedus answered 22/4, 2016 at 7:55 Comment(1)
That is not what I mean, the "123456" is a variable and will always be different. I need to know how I can put that into a variable/console log it.Ovarian

© 2022 - 2024 — McMap. All rights reserved.