2017-12-21 14 views
1

のプロパティ「queryParams」を読み取ることができません私は(角度5を使用して)URLからクエリパラメータを取得しようとしている:は未定義

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(); 
    } 
} 

私は、コンソールログに次のエラーが表示されます。

shop.component.ts:18 Uncaught TypeError: Cannot read property 'queryParams' of undefined

+0

あなたのコンポーネントは ' 'を持つテンプレートに挿入されていますか、それとも独自のセレクタ「'ルートを取得するには、 'router-outlet'タグを使うべきです。 – ConnorsFan

答えて

0

this.sub =のアクセスを無効にしてください。また、あなたがドット経由のparamsを照会するacceesに試すことができます:

this.route.queryParams.subscribe(params => { 
    this.keyword = params.keyword || null; 
}); 
0

それは、エラーの原因となった、私はngOnInit()内部private変数を設定していること、が判明しました。ああ...!

+0

奇妙なことに、エラーは 'this.route'が定義されていないと言いました。 – ConnorsFan