Angular路由

路由:

创建项目时要创建路由。

使用路由  

 * 1.在app-routing.module.ts中引入新建好的组件

 * 2. 配置组件  path:路径  component:组件

const routes: Routes = [

{path:'home',component:HomeComponent},

{path:'news',component:NewsComponent},

{path:'header',component:HeaderComponent},

{path:'newscontent/:aid'  ,component:NewscontentComponent},  ----当用过路由跳转时可以携带参数:aid

//当请求链接没有匹配到路由时,默认访问home组件

//{path:'**',redirectTo:'home'}

];


HTML:

<span>动态路由传值</span>

<ul>

    <li *ngFor="let item of list ;let key=index">

 <a [routerLink]="[ '/newscontent/',key ]" >{{key}}----{{item}}</a>  --newscontent对应路由的path   key为参数

    </li>

</ul>

传值:

 /**

   * 通过url 传值,

   * html: <a [routerLink]="[ '/newscontent' ]" [queryParams]="{aid:key}">{{key}}----{{item}}</a>

   * 在具体组件的业务代码(ts)通过引入ActivedRouter

  import {ActivatedRoute}from '@angular/router'

  在详情组件 构造器声明

 constructor(public route:ActivatedRoute) { }        

 /**获取url中的参数 */

   this.route.queryParams.subscribe((data)=>{

    console.log(data.aid);

    })   

   */

  /**

   * 通过动态路由传值

   * 在app-routing.modules.ts 配置组件的地方  {path:'newscontent/:aid' ,component:NewscontentComponent},

   * 

   * html: <a [routerLink]="[ '/newscontent/',key ]" >{{key}}----{{item}}</a>

   * 

   */

 /**获取动态路由传的值 */

/*    this.route.params.subscribe((data)=>{

      console.log(data.aid);

      })*/


通常在开发过程中还有通过js跳转,获取跳转携带的参数不变,还是如上⬆:

import { Component, OnInit } from '@angular/core';

import {Router,NavigationExtras} from '@angular/router';  

@Component({

  selector: 'app-header',

  templateUrl: './header.component.html',

  styleUrls: ['./header.component.scss']

})

export class HeaderComponent implements OnInit {

  constructor(public router:Router) { }

  ngOnInit(): void {

  }

  /*通过js跳转路由*/ 

  //想通过js进行路由跳转,需要引入router模块

  /**

   * 在构造函数声明

   * 注意:携带参数时 跳转的前提时  目标路由 允许携带参数 在app-routing。modules.ts

   */

  public jumpByJS(){

    /**跳转 */

    this.router.navigate(['/newscontent/','1'])

  }

  public jump(){

    /**通过url传值跳转

     * 引入  NavigationExtras

     * 

     */

    let  queryParams:NavigationExtras={

      queryParams:{'aid':123}   

    };

    this.router.navigate(['/newscontent'],queryParams); 

  }

}

©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

友情链接更多精彩内容