简体   繁体   English

Angular-创建JSON对象以存储与每个路由关联的数据

[英]Angular - Create JSON object to store data associated with each route

I want to create a JSON object which holds help text for each route in the Angular 6 app. 我想创建一个JSON对象,其中包含Angular 6应用程序中每个路由的帮助文本。

let helpRoutes = {
 'wizard/{some_id}/step1': 'This is help content for step 1',
 'wizard/{some_id}/step2': 'This is help content for step 2',
 'user/details/{some_id}/tab1': 'This is help content for user details with activated tab 1'
 'user/details/{some_id}/tab2': 'This is help content for user details with activated tab 2'
}

So if I want to access help for step 1 for any screen_id, I should get it with: 因此,如果我想访问任何screen_id的步骤1的帮助,我应该使用以下方法获得帮助:

helpRoutes['wizard-fa/123456/step4'];

Above code is obviously incorrect and giving me 'undefined' and that is why I asked this question. 上面的代码显然是不正确的,给了我“未定义”,这就是为什么我问这个问题。

Can we achieve what I wanted to do using JSON's key value pair? 我们可以使用JSON的键值对实现我想做的事情吗?

If yes, then how. 如果是,那么如何。 If no, what are the alternatives? 如果没有,有哪些替代方案?

Thanks. 谢谢。

In your routes, you can add static data 在您的路线中,您可以添加静态数据

{ path: 'my-route', component: MyComponent, data: {
  help: 'This is help content for component'
}}

And you can use it with an instance of ActivatedRoute 您可以将其与ActivatedRoute实例一起使用

constructor(
  route: ActivatedRoute
) {
  console.log(route.data);
}

Instead of 代替

let helpRoutes = {
 'wizard/{screen_id}/step1': 'This is help content for step 1',
 'wizard/{screen_id}/step2': 'This is help content for step 2'
}

you can write it as 你可以写成

let helpRoutes = {
 'step1': 'This is help content for step 1',
 'step2': 'This is help content for step 2'
}

Extract the last word using / seperator and get the data from json. 使用/分隔符提取最后一个单词,并从json获取数据。 Like if route is wizard/1234/step1 , get the last word step1 and then help[step1] . 就像route是wizard/1234/step1 ,获取最后一个单词step1 ,然后使用help[step1]

This can be one approach. 这可以是一种方法。

yes you can achieve it by assigning the screen id before calling the helproute object.If you want screen_id to be dynamic then you must have to assing the value to the object first.See the example, 是的,您可以通过在调用helproute对象之前分配屏幕ID来实现。如果希望screen_id是动态的,则必须首先将值赋给该对象。请参见示例,

   let helpRoutes = {};
    for(let screen_id=0;screen_id<10;screen_id++){
        helpRoutes[`wizard/${screen_id}/step1`] =`This is help content for step ${screen_id}`;
    }

After assigning helproutes value you can then get the value. 分配helproutes值后,您可以获取该值。

helpRoutes['wizard/2/step1']

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM