Reputation:
I'm trying to get the query parameters from the url (using Angular 5):
import { Component, OnInit, OnDestroy } from '@angular/core';
import { ActivatedRoute, Router } from '@angular/router';
@Component({
selector: 'app-shop',
templateUrl: './shop.component.html'
})
export class ShopComponent implements OnInit {
constructor(private route: ActivatedRoute, private router: Router) { }
ngOnInit() {
private sub: any;
private keyword: string;
this.sub = this.route.queryParams.subscribe(params => {
this.keyword = params['keyword'] || null;
});
console.log(this.keyword);
}
ngOnDestroy() {
this.sub.unsubscribe();
}
}
I get the following error in the console log:
shop.component.ts:18 Uncaught TypeError: Cannot read property 'queryParams' of undefined
Upvotes: 3
Views: 7228
Reputation:
It turned out, that I've set the private
variables inside the ngOnInit()
, which was causing the error. Huh...!
Upvotes: 1
Reputation: 11696
Try to remove this.sub =
from accessing to route. Also you can try to accees to query params via dot:
this.route.queryParams.subscribe(params => {
this.keyword = params.keyword || null;
});
Upvotes: 0