gpt4 book ai didi

javascript - Angular 2 路由检查参数是否包含有效值

转载 作者:行者123 更新时间:2023-11-30 09:37:50 36 4
gpt4 key购买 nike

我在一个 angular2 组件中有以下代码:

ngOnInit() {
this.route.params
.switchMap((params: Params) => this.elementsService.getElement(+params['id']))
.subscribe(element => {
this.elementToEdit = element;
}
);
}

此组件在两种情况下使用,一种是在 url 中提供了 id,另一种是没有提供 id。在第一种情况下,它工作正常。在第二个中,它可以工作,但控制台中出现 404 错误:api/elements/NaN

我正在尝试解决这个问题,但我找不到检查 id 是否在 url 中的方法:

ngOnInit() {
if(this.route.params['id']){<---doesn't work
this.route.params
.switchMap((params: Params) => this.elementsService.getElement(+params['id']))
.subscribe(element => {
this.elementToEdit = element;
}
);
}
}

如果 id 参数不存在,是否有办法做到这一点并避免调用服务?

最佳答案

我在我的一个项目中使用它,对我来说效果很好

this.route.params.subscribe((params: any) => {
if (params.id) {
// Edit your element here
} else {
// Create your new element here
}
});

我的路线是这样的

{ path: "home/:id", component: HomeComponent },

关于javascript - Angular 2 路由检查参数是否包含有效值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42635348/

36 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com