Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Retrieve data from url wiith params in angular2

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.

like image 906
Mikkel Avatar asked Jan 20 '26 05:01

Mikkel


2 Answers

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

 }

https://angular.io/docs/ts/latest/api/router/index/ActivatedRoute-interface.html#!#queryParams-anchor

like image 185
slaesh Avatar answered Jan 21 '26 18:01

slaesh


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");
           }
      });
}
like image 25
Joe Keene Avatar answered Jan 21 '26 18:01

Joe Keene



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!