Angular 2 的异步加载路由数据和构建路由指令 [英] Async load routes data and build route instruction for Angular 2

查看:22
本文介绍了Angular 2 的异步加载路由数据和构建路由指令的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试从 angular2 动态构建路由(从服务器获取路由配置),然后解析它并为组件路由生成指令(我有父路由配置和子路由到不同的组件,因为我不知道如何定义将子组件路由到一个 main.app.ts 文件中).

I try to build dynamically routes from angular2 (fetch route config from server), after that I parse it and generate instruction for component route (I have parent routes config and child into different components, because I don`t know how define route for child component into one main.app.ts file).

问题是当应用程序启动并尝试创建路由配置并且 routeGenerator 尚未构建路由(异步延迟)时,无法解析路由数据(因为异步延迟,因此现在未定义 routesData)并且应用程序崩溃了.我不知道该怎么办.寻找生命周期引擎盖(有些像 - @Angular2BeforeAppStarted )但什么也没找到.

The problem is when app started and try to create routes config and routeGenerator is not build routes yet (async delay) cant parse routes data (because async delay, so routesData undefined now) and app is crashig. I dont know what to do with this. Looking for lifecycle hood (some like - @Angular2BeforeAppStarted ) but found nothing.

    import {Component, Input, OnChanges} from 'angular2/core';
import {RouteConfig, RouterOutlet, ROUTER_DIRECTIVES, Router} from 'angular2/router';
/* ------- !Angular 2 native components  ---------*/
import {routeGenInstance} from '../../config/routes/patient_routes';


protected const BUILT_MODULE_PATH: string = '/built/modules/patients/';

@Component({
  template: `
    <router-outlet ></router-outlet>
  `,
  directives: [RouterOutlet, ROUTER_DIRECTIVES]
})
@RouteConfig(routeGenInstance.getRouteDefinitions())

export class PatientsComponent {
  @Input();

  constructor() {}

}

我也尝试以相同的方式更新路线(但应用程序立即崩溃,因为导航组件中的导航链接没有正确的链接方式)

Also i try to update routes in the same way (but app is crashed immediately because my Navigation link in navigation component is not have some correct link way)

import {RouteConfig, RouterOutlet, ROUTER_DIRECTIVES, Router} from 'angular2/router';

     constructor(
        private router: Router
         ) {
        router.config([
             routeGenInstance.getRoutesDefinition()
        ])
      }

我的路由定义使用异步加载器,因此它们是正确的并且可以在没有异步延迟的情况下工作.我不知道如何让 Angular 等待我的路线定义并开始运行应用程序.

my route definitions use Async loader so they are correct and work whithout async delay. I don`t know how to make angular wait for my routes definitions and thet start to run the app.

请帮帮我.谢谢.

UPD:

@Thierry 再次感谢您的帮助.你真棒,我的朋友和导师.最后一个问题(最后一个).你能告诉我如何将 routeConfig 定义到一个带有子子路由定义的应用程序文件中吗?它的意思.我有进入应用程序文件的主要级别路由

@Thierry many thanks for your help again. You are awesome my friend and mentor. One last question (last). Can you tell me how I can define routeConfig into one app file with child subrouting definition? Its mean. I have main level routes into app files

{
  path: '/',
  name: 'Dashboard',
  component: DashboardComponent,
  useAsDefault: true
},
{
  path: '/patients/...',
  name: 'Patients',
  component: PatientsComponent
},

和患者子路由进入患者组件(@RouteConfig)

and patient sub routes into patientsComponent (@RouteConfig)

{
  path: '/',      // root is appRoot/patients/...
  name: 'PatientsList', component...},
  {
  "name": "Chart",
  "path": "/chart/:id", component...
},

如何将此路由配置仅定义到一个 app.file 中?(如何在一个文件中配置带有子路由的路由)?

How to define this route config only into one app.file ? (How to configure route with sub routing in one file)?

推荐答案

一个选项可能是在引导您的应用程序之前获取您的配置.

An option could be to get your configuration before bootstrapping your application.

var injector = Injector.resolveAndCreate([HTTP_PROVIDERS]);
var http = injector.get(Http);

http.get('routes.json').map(res => res.json())
  .subscribe(data => {
    bootstrap(AppComponent, [
      HTTP_PROVIDERS
      provide('routesConfig', { useValue: data })
    ]);
  });

然后你可以通过依赖注入和同步的方式访问路由配置:

Then you can have access the routes configuration by dependency injection and in a synchronous way:

@Component({
  (...)
})
export class AppComponent {
  constructor(@Inject('routesConfig') private routesConfig, private router:Router) {
    // Configure here your routes
  }
}

这两个问题可以帮助你:

These two questions could help you:

编辑

您可以利用 Observable.forkJoin 方法从不同的请求中加载您的路由配置:

You can leverage the Observable.forkJoin method to load your route configuration from different requests:

var injector = Injector.resolveAndCreate([HTTP_PROVIDERS]);
var http = injector.get(Http);

Observable.forkJoin([
  http.get('mainRoutes.json'),
  http.get('childRoutes.json')
])
.map(responses => {
  return {
    main: res[0].json(),
    children: res[1].json()
   };
 })
  .subscribe(data => {
    bootstrap(AppComponent, [
      HTTP_PROVIDERS
      provide('routesConfig', { useValue: data })
    ]);
  });

编辑1

我认为你可以尝试这样的事情:

I think that you could try something like that:

[
  {
    path: '/patients/...',
    name: 'Patients',
    component: PatientsComponent,
    childRoutes: [
      {
        path: '/',      // root is appRoot/patients/...
        name: 'PatientsList', component...
      },
      (...)
    ]
  }
]

但是你需要根据你要处理的提示,对内容进行拆分,得到不同的元素:

But you need to split the content to get different elements according to the hints you want to handle:

  • 一个用于根:

  • one for the root:

[
  {
    path: '/patients/...',
    name: 'Patients',
    component: PatientsComponent
  }
]

  • 有几个适合儿童的.以患者为例:

  • several for children. For example for patients:

    [
      {
        path: '/',      // root is appRoot/patients/...
        name: 'PatientsList', component...
      },
      (...)
    ]
    

  • 这篇关于Angular 2 的异步加载路由数据和构建路由指令的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆