角5:如何获取当前的queryparams [路由]

its*_*vid 0 javascript routing query-parameters typescript angular

我在尝试将queryparams放入组件时遇到麻烦。现在,我只想要console.log(...)它。我正在使用ActivatedRoutefrom @angular/router这个任务。

我正在重新开发某个工作平台,因此不幸的是,一些不相关的代码将必须替换为“ ...”

我的Component.ts代码:

import { Component, OnInit, ViewEncapsulation } from '@angular/core';
import { RelevantReportService } from './../reportServices/relevantReports.service';
import { ActivatedRoute ,Params, Router } from '@angular/router';

@Component({
  selector: 'vr-reports',
  templateUrl: './reports.component.html',
  styleUrls: ['./reports.component.scss'],
  providers: [RelevantReportService],
  encapsulation: ViewEncapsulation.None
})
export class ReportsComponent implements OnInit {

  reportSections: any;
  constructor( private relevantReportService: RelevantReportService,
               private router: Router,
               private activatedRoute : ActivatedRoute

             ) { }

  ngOnInit() {
   ...

    console.log(this.activatedRoute.queryParams.value.reportName)
    // console.log(this.activatedRoute.queryParams._value.reportName)
  }
...

}
Run Code Online (Sandbox Code Playgroud)

当我这样做时console.log(this.activatedRoute.queryParams.value.reportName),控制台会吐出queryparams(这正是我想要的),但是它也说

“类型为“可观察”的属性“值”不存在”

所以我认为这不是解决问题的正确方法。

Nik*_*kov 6

它是可观察的,以便能够监视参数中的变化(通过订阅observable)。要获取当前传递的查询参数,请使用:

this.activatedRoute.snapshot.queryParams
Run Code Online (Sandbox Code Playgroud)

您也可以使用ActivatedRouteSnapshot而不是ActivatedRoute

  • 并请注意,如果使用快照,则使用不同的查询参数重新显示页面时不会通知您。 (3认同)