最近开始学习angular框架,路由部分怎么学呢?我想通过自己一边写demo,一边用文字记录下这个过程,让自己学习到的内容更加深刻。以下就开始直播学习过程:
一、安装路由文件到模版
首先,用ngcli新建一个配置好路由文件名为“ngRouter”的项目:
在命令工具输入
ng new ngRouter --routing
安装完毕后,会在项目文件中的src/app中看到一个名为“app-routing.module.ts”的文件,

里面的代码是这样的:
import{NgModule}from'@angular/core'; //第一行
import{Routes,RouterModule}from'@angular/router'; //第二行
const routes:Routes=[]; //第三行
@NgModule({ //第四行
imports:[RouterModule.forRoot(routes)], //第五行
exports:[RouterModule] //第六行
})
export class AppRoutingModule { } //第七行
代码中的第一行是导入NgModule,第二行导入配置路由用的Routes和RouterModule类,第三行声明一个Routes类型的常量,用以配置路由的参数,第五行是将定义的路由注入到NgModule中,第七行是本文件的出口,会在“app.module.ts”文件中导入:

二、新建两个用于演示的组件
在命令行工具中输入

在项目中生成了两个组件(demo1和demo2)

三、实现简单的路由
到“app-routing.module.ts”文件,给routes常量赋值,即在中括号中输入内容,routes是一个数组,元素可以看作是每一个要配置的路由。在这,分别给demo1和demo2配置路由,输入内容如下:

在app组件中写入可以实现跳转的a标签,“app.component.html”的内容写成:

接着运行在浏览器中(在命令行工具输入npm start)
页面中出了:

点击之后就会显示相应的组件
3.1路由重定向
如果需要进入主页就开始显示组件demo1的内容,则在“app-routing.module.ts”配置对应的属性,如下:

3.2按钮实现跳转
不论是什么元素的什么事件,都可以触发路由跳转。用简单的按钮点击事件作示范:
首先,在“app.component.html”中添加一个按钮:

接着,在“app.component.ts”中定义点击相对应的函数(这里是"linkToDemo2"):

这样点击按钮就可以跳转路由了。
注意:需要导入Router,然后在构造函数中注入,写在navigate的参数是个数组。
3.3无定义路由跳转到404页面
在现实中,如果用户输入路由错误或没有定义的路由,这时,应该跳转到一个404页面。项目中,实现的步骤如下:
1、写好一个404页面组件,并写上要显示的内容。

2、在路由中设置好配置

关键: 这里用到了“**”作通配符,一定要把这个对象放到最后,因为,路由是按顺序找组件的,如果放在前面,就首先跳到404组件,不会再找后面的组件。
3.4路由传参的应用
在路由中定义一个参数,用户输入是什么值,那么这个参数就被定义成什么值,简单的应用如下:

我demo1的路由中添加了id的参数,当我要在页面中使用这个参数时,那么,需要在组件中的TS文件写些代码,本例是在“demo1.component.ts”中写,如果我要动态显示这个参数:
1、在“demo1.component.ts”写:

2、在相应的HTML文件就可以使用定义好的变量了(我定义成userId)

效果:

当然,可以在a标签中写好id

还有,另外一种方法,写参数

还有还有,另外一种方法传参数:

然后,在“demo1.component.ts”中写成:

路径是会就这样的

最后,还有一种传数据的方法:
在路由配置文件中,加上属性data:

在“demo1.component.ts”中写成:

--------------------------------------------------------------------------------
路由基本的应用就写到这里了,后面还有一个路由防卫,接下来将另写一篇走一遍。
总结
介绍了模块导入路由,用两个简单的组件演示了路由的使用,包括了:普通跳转、事件触发跳转、路由重定向、无定义的路由跳转到404组件和路由的数据传输。
网友评论