I want to get the query string parameters. I could do it in the component's constructor()
or in ngOnInit()
. Also, there are two ways to do that:
// option (1)
const foo = this.activatedRoute.snapshot.queryParamMap.get("foo");
//use foo...
// option (2)
const subscription = this.activatedRoute.queryParamMap.subscribe(params => {
const foo = params["foo"];
//use foo...
});
// ...and remember to unsubscribe in `ngOnDestroy()`
There are lots of questions from people who have trouble getting the query string, and the answer is always to use option (1) or (2), but there's never an explanation why. I've used both ways and I've never had a problem, so far.
So:
- when should I use (1) and when should I use (2)?
- should I do it in the
constructor()
orngOnInit()
?