gpt4 book ai didi

javascript - Angular:在嵌套数组中查找键/值

转载 作者:行者123 更新时间:2023-11-28 03:42:51 25 4
gpt4 key购买 nike

描述:
我有一个 module.ts ,它有一个处理路由的 const Route 。在此 route ,我在 data 下有一个名为 sidebar 的键。

const routes: Routes = [{
path: 'devices',
component: BaseComponent,
children: [{
path: '',
component: DeviceListComponent,
data: {
sidebar: true
}
}]
}];

我想做的事情:
我希望能够在我的 component.ts 中遍历这个数组,如果找到 sidebar,并且 sidebar 的值为 true, path 名称将显示在 div 中。
例如,对于 path:'device'sidebar 为 true,因此我的 div 中将包含一个文本,表示 device.

我尝试做的事情/问题:
我不知道如何找到 sidebar 键。在我的 component.ts 文件中,我可以通过 router.config 成功获取数组,但我无法弄清楚找到 key 的逻辑。

ngOnInit() {     
var theArray= this.router.config; //Grabs array successfully!
for (let obj of theArray) {
console.log("object:", theArray); //prints our array
for (let sidebar in obj) {
console.log("key:", sidebar, "value:", obj[sidebar]);
}
}
}

我从第二个 console.log 得到的结果是:

console.log

最佳答案

我认为这里的主要问题是你不应该做你正在做的事情:)当然,有一种方法可以实现您想要做的事情,通过以某种复杂的方式解析路由器配置 - 但是您想要实现的事情,可以通过使用预期的方式更容易地完成。

一种方法是使用 Angular 的解析数据功能,以便将所需的变量获取到组件中。

所以你的路线看起来像这样

{
path: '',
component: DeviceListComponent,
resolve: {
sidebar: true
}
}

在你的组件中你会做这样的事情

constructor(private route: ActivatedRoute) {}

ngOnInit() {
this.hasSidebar= this.route.snapshot.data['sidebar'];
}

有关该主题的更深入的教程,您可以查看此博客文章,例如: https://blog.thoughtram.io/angular/2016/10/10/resolving-route-data-in-angular-2.html

关于javascript - Angular:在嵌套数组中查找键/值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48792162/

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