Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Proper way to get queryParams with Angular2 RC6

Please only provide answers current for RC6 and above.

I recently attempted to upgrade from RC1 to RC6 and found RouteSegment is gone. After a lot of digging, I've found ActivatedRoute, however it appears to be WAY over complicated for pulling out a raw value from the url.

Is the new correct way to read a static query value the following?

const id : Observable<number> = this.route.queryParams.map(p => p.id);

If so, can some please explain why I need a map and an observable just to pull the value 6 out of the URL's query string?

Can someone please explain what new cool feature I have at my disposal to warrant this much increase in code complexity?

If I'm missing something obvious, please point me in the right direction. I'd prefer to stick to a simple URL query system like: let id = params.id;

Thanks

like image 573
Luke Dupin Avatar asked Sep 06 '16 03:09

Luke Dupin


1 Answers

import { Component, OnDestroy } from '@angular/core';
import { ActivatedRoute } from "@angular/router";
import { Subscription } from "rxjs/Rx";

@Component({
    moduleId: module.id,
    selector: 'app-home-component',
    template: `
                <h1>
                    Home Component!
                </h1>
                <hr>
                {{param}}
              `,
    styles: []
 })

export class HomeComponent implements OnDestroy {
    private subscription: Subscription;

    param: string;

    constructor(private route: ActivatedRoute) {
         this.subscription = route.queryParams.subscribe(
             (queryParam: any) => this.param = queryParam['paramName']
         );
    }

    ngOnDestroy() {
        this.subscription.unsubscribe();
    }
}

You can also use snapshot (less code) ex: let foo = this.route.snapshot.queryParams['foo']; if your component is not reusable. Otherwise this snapshot will be only created once and will not change when you re-navigate to the same component with different param (meaning changing just a parameter in current url).

Here's the example:

Let's say you're at mydomain/mycomponent?id=1

You can use a subscription to Observable queryParams or snapshot to get the 'id' parameter value. Results will be the same.

Now navigate to mydomain/mycomponent?id=2 and using subscription you will get '2' as a value, but using snapshot it will still be '1'.

like image 199
rook Avatar answered Oct 19 '22 03:10

rook