In my routable component
I have
@RouteConfig {
{path: \'/login\', name: \'Login\', component: LoginComponent}
}
But how
In Angular 6, I found this simpler way:
navigate(["/yourpage", { "someParamName": "paramValue"}]);
Then in the constructor or in ngInit
you can directly use:
let value = this.route.snapshot.params.someParamName;
This worked for me (as of Angular 2.1.0):
constructor(private route: ActivatedRoute) {}
ngOnInit() {
// Capture the token if available
this.sessionId = this.route.snapshot.queryParams['token']
}
(For Childs Route Only such as /hello-world)
In the case you would like to make this kind of call :
/hello-world?foo=bar&fruit=banana
Angular2 doesn't use ? nor & but ; instead. So the correct URL should be :
/hello-world;foo=bar;fruit=banana
And to get those data :
import { Router, ActivatedRoute, Params } from '@angular/router';
private foo: string;
private fruit: string;
constructor(
private route: ActivatedRoute,
private router: Router
) {}
ngOnInit() {
this.route.params.forEach((params: Params) => {
this.foo = params['foo'];
this.fruit = params['fruit'];
});
console.log(this.foo, this.fruit); // you should get your parameters here
}
Source : https://angular.io/docs/ts/latest/guide/router.html
According to Angular2 documentation you should use:
@RouteConfig([
{path: '/login/:token', name: 'Login', component: LoginComponent},
])
@Component({ template: 'login: {{token}}' })
class LoginComponent{
token: string;
constructor(params: RouteParams) {
this.token = params.get('token');
}
}
The route.snapshot provides the initial value of the route parameter map. You can access the parameters directly without subscribing or adding observable operators. It's much simpler to write and read:
Quote from the Angular Docs
To break it down for you, here is how to do it with the new router:
this.router.navigate(['/login'], { queryParams: { token:'1234'} });
And then in the login component (notice the new .snapshot
added):
constructor(private route: ActivatedRoute) {}
ngOnInit() {
this.sessionId = this.route.snapshot.queryParams['token']
}
For Angular 4
Url:
http://example.com/company/100
Router Path :
const routes: Routes = [
{ path: 'company/:companyId', component: CompanyDetailsComponent},
]
Component:
@Component({
selector: 'company-details',
templateUrl: './company.details.component.html',
styleUrls: ['./company.component.css']
})
export class CompanyDetailsComponent{
companyId: string;
constructor(private router: Router, private route: ActivatedRoute) {
this.route.params.subscribe(params => {
this.companyId = params.companyId;
console.log('companyId :'+this.companyId);
});
}
}
Console Output:
companyId : 100