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
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'.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With