【问题标题】:Angular 8 ActivatedRoute Params are not gettingAngular 8 ActivatedRoute 参数没有得到
【发布时间】:2020-08-12 12:56:41
【问题描述】:

我在尝试以下方法时,在角度使用 ActivatedRoute 时从 url 获取参数时遇到问题。

app-routing.module.ts

import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { PartPriceComponent } from './part-price/part-price.component';


const routes: Routes = [
  { path: "product/:device", component: PartPriceComponent }
];

@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule]
})
export class AppRoutingModule { }

part-price.component.ts

import { Component, OnInit } from '@angular/core';
import { ActivatedRoute } from "@angular/router";

@Component({
  selector: 'app-part-price',
  templateUrl: './part-price.component.html',
  styleUrls: ['./part-price.component.css']
})
export class PartPriceComponent implements OnInit {
  public deviceSelectedVal: any;
  constructor(private route: ActivatedRoute) {
     this.route.paramMap.subscribe(
       (params: any) => {
         this.deviceSelectedVal = params.get('device');
     })
    }
    
    ngOnInit(): void {
    console.log('this.deviceSelectedVal', this.deviceSelectedVal)
  }
}

我正在尝试传递这样的 URL:http://localhost:4200/product/pixel

【问题讨论】:

    标签: angular angular-router


    【解决方案1】:

    如果您不打算在访问它的同一组件中更新device 参数,那么您可以从快照中获取它。 this.route.snapshot.paramsMap.get('device')

    【讨论】:

    • Nikolay 我也在尝试这个,但仍然为空
    【解决方案2】:

    只需尝试订阅已激活路由上的参数即可。像这样,

    this.route.params.subscribe((params) => {
        this.deviceSelectedVal = params['device'];
        console.log('New device detected', this.deviceSelectedVal);
    })
    

    在 ngOnInit 生命周期钩子中添加订阅,或者保持在构造函数中添加订阅的方式(但构造函数应该只用于初始化类成员,而不应该做实际的“工作”)。

    【讨论】:

      【解决方案3】:

      尝试在 ngOnInit 下提供您的逻辑。我希望这能解决您的问题。

      ngOnInit() {
        this.route.paramMap.subscribe(
             (params: any) => {
               this.deviceSelectedVal = params.get('device');
           });
      }
      

      【讨论】:

      • 是的,我正在尝试在 ngOnInit 下构建我的逻辑,但我仍然没有在参数中得到任何东西。我的参数值得到空对象 {}
      【解决方案4】:

      this.route.params.subscribe 是异步的,所以console.log('this.deviceSelectedVal', this.deviceSelectedVal) 这会在this.deviceSelectedVal = params.get('device'); 之前被调用

      this.deviceSelectedVal = params['device'];下方添加您的console.log

      【讨论】:

      • 试试这个但仍然得到空值
      猜你喜欢
      • 2016-12-20
      • 1970-01-01
      • 1970-01-01
      • 2019-08-26
      • 2021-06-28
      • 2018-06-13
      • 2017-12-14
      • 2019-12-03
      • 1970-01-01
      相关资源
      最近更新 更多