(精华)2020年8月6日 Angular 路由的使用
发布日期:2021-06-29 15:08:58 浏览次数:2 分类:技术文章

本文共 2377 字,大约阅读时间需要 7 分钟。

Angular 中的路由

一、 Angular 创建一个默认带路由的项目

  1. 命令创建项目

ng new ng-demo --skip-install

在这里插入图片描述

  1. 创建需要的组件
ng g component components/homeng g component components/newsng g component components/newscontent
  1. 找到 app-routing.module.ts 配置路由

引入组件

import {
HomeComponent } from './components/home/home.component';import {
NewsComponent } from './components/news/news.component';import {
ProductComponent } from './components/product/product.component';

配置路由

const routes: Routes = [{
path: 'home', component: HomeComponent},{
path: 'news', component: NewsComponent},{
path:'product', component:ProductComponent },{
path: '*', redirectTo: '/home', pathMatch: 'full' }];
  1. 找到 app.component.html 根组件模板,配置 router-outlet 显示动态加载的路由

首页 新闻

二、Angular routerLink 跳转页面默认路由

首页新闻
//匹配不到路由的时候加载的组件 或者跳转的路由{
path: '**', /*任意的路由*/ // component:HomeComponent redirectTo:'home'}

三、Angular routerLinkActive 设置 routerLink 默认选中路由

首页 新闻

首页 新闻

四、动态路由

4.1.问号传参

跳转方式,页面跳转或js跳转

问号传参的url地址显示为 …/list-item?id=1

queryParams属性是固定的

<a [routerLink]="[’/list-item’]" [queryParams]="{id:item.id}">

{
{ item.name }}

//js跳转

//router为ActivatedRoute的实例

import {
Router } from '@angular/router';.constructor(private router: Router) {
}.this.router.navigate(['/newscontent'],{
queryParams:{
name:'laney', id:id }, skipLocationChange: true //可以不写,默认为false,设为true时路由跳转浏览器中的url会保持不变,传入的参数依然有效});

获取参数方式

import {
ActivatedRoute } from '@angular/router';constructor(public route:ActivatedRoute) {
}ngOnInit() {
this.route.queryParams.subscribe((data)=>{
console.log(data); })}

4.2 路径传参

路径传参的url地址显示为 …/list-item/1

<a [routerLink]="[’/list-item’, item.id]">

{
{ item.name }}

//js跳转

//router为ActivatedRoute的实例

this.router.navigate([’/list-item’, item.id]);

路径配置:

{path: ‘list-item/:id’, component: ListItemComponent}

获取参数方式

this.route.params.subscribe(  param => {
this.id= param['id']; })

五、父子路由

  1. 创建组件引入组件

import { WelcomeComponent } from ‘./components/home/welcome/welcome.component’;

import { SettingComponent } from ‘./components/home/setting/setting.component’;

  1. 配置路由
{
path:'home', component:HomeComponent, children:[{
path:'welcome', component:WelcomeComponent },{
path:'setting', component:SettingComponent }, {
path: '**', redirectTo: 'welcome'} ]},
  1. 父组件中定义router-outlet

转载地址:https://codeboy.blog.csdn.net/article/details/107852357 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!

上一篇:(精华)2020年8月7日 微信小程序 导航的使用
下一篇:(精华)2020年8月6日 Angular axio的封装

发表评论

最新留言

不错!
[***.144.177.141]2024年04月24日 05时18分00秒