如何解决Angular 8 ActivatedRoute参数没有得到
我在尝试使用以下方法时,在使用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');
});
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。