Proper way to get queryParams with Angular2 RC6

浪子不回头ぞ 提交于 2019-12-10 04:17:18

问题


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


回答1:


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'.



来源:https://stackoverflow.com/questions/39340193/proper-way-to-get-queryparams-with-angular2-rc6

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!