问题描述
我在尝试使用以下方法时,在使用Angled中的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
解决方法
this.route.params.subscribe
是异步的,因此console.log('this.deviceSelectedVal',this.deviceSelectedVal)
将在this.deviceSelectedVal = params.get('device');
之前被调用
在this.deviceSelectedVal = params['device'];
下方添加您的console.log
如果您不打算在要访问的同一组件中更新device
参数,则可以从快照中获取它。
this.route.snapshot.paramsMap.get('device')
只需尝试在激活的路线上订阅参数。像这样
this.route.params.subscribe((params) => {
this.deviceSelectedVal = params['device'];
console.log('New device detected',this.deviceSelectedVal);
})
将订阅添加到ngOnInit生命周期挂钩中,或将其保留为在构造函数中添加订阅的方式(但是构造函数应仅用于初始化类成员,而不能执行实际的“工作”)。
,尝试在ngOnInit下提供您的逻辑。我希望这能解决您的问题。
ngOnInit() {
this.route.paramMap.subscribe(
(params: any) => {
this.deviceSelectedVal = params.get('device');
});
}