【问题标题】:Cannot read property 'queryParams' of undefined无法读取未定义的属性“queryParams”
【发布时间】:2017-12-21 14:52:03
【问题描述】:

我正在尝试从 url 获取查询参数(使用 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();
    }
}

我在控制台日志中收到以下错误:

shop.component.ts:18 未捕获类型错误:无法读取属性 未定义的'queryParams'

【问题讨论】:

  • 您的组件是使用<router-outlet></router-outlet> 还是直接使用自己的选择器<app-shop></app-shop> 插入到模板中?为了获得路由,你应该使用router-outlet标签。

标签: angular


【解决方案1】:

事实证明,我在ngOnInit() 中设置了private 变量,这导致了错误。哼……!

【讨论】:

  • 奇怪:错误说this.route是未定义的。
【解决方案2】:

尝试从访问路由中删除this.sub =。您也可以尝试通过 dot 访问参数:

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

【讨论】:

    猜你喜欢
    • 2021-03-28
    • 1970-01-01
    • 2020-04-06
    • 2020-10-30
    • 2019-10-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多