您好,欢迎访问一九零五行业门户网

如何使用Angular内Router(路由)应用

这次给大家带来如何使用angular内router(路由)应用,使用angular内router(路由)应用的注意事项有哪些,下面就是实战案例,一起来看一下。
序言:
angular app 视图之间的跳转,依赖于 router (路由),这一章,我们来讲述 router 的应用
实例讲解
运行结果如下。 设置了3个导航栏, home、 about、dashboard。 点击不同的导航栏,跳转到相应的页面:
创建3个 component
ng g c home
ng g c about
ng g c dashboard
路由与配置
(1)**引入 angular router **
当用到 angular router 时,需要引入 routermodule,如下:
// app.module.ts import { routermodule } from '@angular/router'; imports: [  browsermodule, routermodule ],
(2) 路由配置
还记得由谁来管理component 的吧,没错,由 module 来管理。 所以,把新创建的 component,引入到 app.moudle 中。 如下:
import { browsermodule } from '@angular/platform-browser'; import { ngmodule } from '@angular/core'; import { routermodule } from '@angular/router'; import { approutes } from './routerconfig'; import { appcomponent } from './app.component'; import { aboutcomponent } from './components/about/about.component'; import { homecomponent } from './components/home/home.component'; import { dashboardcomponent } from './components/dashboard/dashboard.component';
提示: 注意component的路径,为便于管理,我们把新创建的component 移到了 components 文件夹中。
创建 router configure 文件
在 app 目录下, 创建 routerconfig.ts 文件。 代码如下:
import { routes } from '@angular/router'; import { homecomponent } from './components/home/home.component'; import { aboutcomponent } from './components/about/about.component'; import { dashboardcomponent } from './components/dashboard/dashboard.component'; export const approutes: routes = [  { path: 'home',   component: homecomponent   },  {  path: 'about',  component: aboutcomponent  },  { path: 'dashboard',  component: dashboardcomponent  } ];
说明: angular 2.x 以上版本,开始使用 typescript 编写代码,而不再是 javascript,所以,文件的后缀是: ts 而不是 js
这个 routerconfigue 文件,怎么调用呢? 需要把它加载到 app.module.ts 中,这是因为 app.moudle.ts 是整个angular app 的入口。
// app.module.ts import { approutes } from './routerconfig'; imports: [  browsermodule,  routermodule.forroot(approutes) ],
声明 router outlet
在 app.component.html 文件中,添加代码:
<p style="text-align:center">  <h1>   {{title}}!!  </h1>  <nav>   <a routerlink="home" routerlinkactive="active">home</a>   <a routerlink="about">about</a>   <a routerlink="dashboard">dashboard</a>  </nav>  <router-outlet></router-outlet>  </p>
运行
进入到该工程所在的路径, 运行;
ng serve --open
当 webpack 编译成功后,在浏览器地址栏中,输入: http://localhost:4200
即可看到本篇开始的结果。
关于router,换一种写法:
在 app.moudle.ts 文件中,代码如下 :
imports: [   browsermodule,   routermodule.forroot(   [    { path: 'home',     component: homecomponent     },    {    path: 'about',    component: aboutcomponent    },    {    path: 'dashboard',    component: dashboardcomponent    }   ]   )  ],
这样一来,可以不用单独创建 routerconfigure.ts 文件。
小结
自从引入了面向组件(component)后,路由管理相比 angularjs (1.x),方便了很多。
进一步优化:
或许你已经注意到,当访问 http://localhost:4200 时,它的路径应该是 “/”, 我们应该设置这个默认的路径。
{    path: '',    redirectto:'/home',    pathmatch: 'full'    },
相信看了本文案例你已经掌握了方法,更多精彩请关注其它相关文章!
推荐阅读:
怎样使用js做出动态添加html标记
从零开始使用react router v4
以上就是如何使用angular内router(路由)应用的详细内容。
其它类似信息

推荐信息