当前位置: 移动技术网 > IT编程>脚本编程>AngularJs > Angular2 路由问题修复详解

Angular2 路由问题修复详解

2018年05月01日  | 移动技术网IT编程  | 我要评论

angular2 提供了比angular1 更为强大的路由功能,但是在具体使用路由过程中,可是出现了很多路由不按照预想的方式执行的问题。为了说明今天的问题,我特地新建了一个测试工程。欢迎交流。

首先介绍一下测试代码的组织结构,

其中包含两个组件:button、accordion。这个例子采用的是ng2-bootstrap.

我展示一下路由配置:

/**
 * created by guozhiqi on 2017/2/24.
 */
import {route,routes}from '@angular/router';
import {appcomponent}from './app.component';
import {layoutcomponent}from './layout/layout.component';

export const routes:routes=[
 {
  path:'',
  redirectto:'button',
  pathmatch:'full'
 },
 {
  path:'',
  component:layoutcomponent,
  children:[
   {
    path:'button',
    loadchildren:'./button/button-guo.module#buttonguomodule'
   },
   {
    path:'accordion',
    loadchildren:'./accordionguo/accordion-guo.module#accordionguomodule'
   }
  ]
 },
 {
  path:'**',
  redirectto:'button',
 }
];

这段路由中我定义了默认路由,会跳转到button,但是我采用最新的angular-cli,并没有进行跳转,并且默认路由并没有使用layoutcomponent组件,这是最大的问题,因为layoutcomponent组件是整个页面的样式文件。

目前的结果什么呢?

我展示一下appmodule.ts代码:

import { browsermodule } from '@angular/platform-browser';
import { ngmodule } from '@angular/core';
import { formsmodule } from '@angular/forms';
import { httpmodule } from '@angular/http';
import {buttonguomodule}from './button/button-guo.module';
import { appcomponent } from './app.component';
import {buttonsmodule}from 'ng2-bootstrap/buttons';
import {routes}from './app.routing';
import {routermodule}from '@angular/router';
import {commonmodule}from '@angular/common';
import {accordionguomodule}from './accordionguo/accordion-guo.module';
import {layoutcomponent}from './layout/layout.component';
@ngmodule({
 declarations: [
  appcomponent,layoutcomponent
 ],
 imports: [routermodule.forroot(routes),accordionguomodule,
  browsermodule,routermodule,commonmodule,
  formsmodule,buttonguomodule,
  httpmodule
 ],
 providers: [],
 bootstrap: [appcomponent]
})
export class appmodule { }

请注意appmodule.ts中我标红的引入module,如果我将accordionmodule放在buttonmodule前面,那么显示的就是accordionmodule的内容,反之显示的就是buttonmodule的内容。

执行结果:

1.accordionmodule在buttonmodule前面

2.buttonmodule在accordionmodule前面

请注意,更改了顺序以后,务必重新编译,重新执行 ng serve命令。

会什么会出现这个问题?欢迎大家交流。下篇我会专门解释这个问题的答案

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网