Reputation: 1811
I'm having a hard time getting the data from my query string when using routerLink to navigate to another component. Have done after the dokumentation from angular.io, so I'm not sure what is wrong.
Component 1:
This component contain the routerLink which look like this:
<div class="column small-12 large-8 gutter-xsmall-up end waiting">
Could not find the movie, please go <a [routerLink]="['/request']" [queryParams]="{id:MovieFromImdb.Id, title: MovieFromImdb.Title}">request it</a>
</div>
This produces this url:
http://localhost:3000/request?id=tt0117500&title=The%20Rock
Component 2:
In this component, I need to retrive the data, but somehow it only stay undefined when using console.log.
Here is what I have tried.
import { Component } from '@angular/core';
import { AppState } from '../app.service';
import { Params, ActivatedRoute } from '@angular/router';
export class Request {
private typeArray: Array<any>;
private defaultSelection: number;
private Title: string;
private Link: string;
constructor(public requestService: RequestService, private route: ActivatedRoute,) {
this.defaultSelection = 2;
this.typeArray = requestService.createList();
}
requestMovie(title, link, quality) {
console.log(title, link, quality);
}
ngOnInit() {
this.route.params.forEach((params: Params) => {
this.Title = params['title'];
this.Link = params['id'];
});
console.log(this.route.snapshot.params['id'])
console.log(this.route.snapshot.params['title'])
}
}
Can any see what I have done wrong here?
Using the newest angular2 release.
Upvotes: 3
Views: 7636
Reputation: 2351
You can use subscribe to the route params like so:-
ngOnInit() {
this.route.params.subscribe(params => {
for(let param in params ) {
console.log(param, "the param");
}
});
}
Upvotes: 2
Reputation: 16917
It's quite easy, you should use queryParams
instead of params
.
ngOnInit() {
this.route.queryParams.forEach((params: Params) => {
this.Title = params['title'];
this.Link = params['id'];
});
console.log(this.route.snapshot.queryParams['id'])
console.log(this.route.snapshot.queryParams['title'])
}
Upvotes: 2