Angular - 路由相关

1. 创建项目, 并同时生成路由文件

2. 创建组件xxx

3. 配置路由, 并在routing文件中导入组件xxx

    const routes: Routes = [
      {path: 'xxx', component: XxxComponent}
    ];

4. 在使用的地方用 routerLink
    <a [routerLink]="[ '/xxx' ]">跳转xxx页面</a>

5. 跳转的页面会显示在<router-outlet></router-outlet>位置

6. 配置默认路由
    const routes: Routes = [
      {path: 'xxx', component: XxxComponent},
      {path: '**', redirectTo: 'xxx'}
    ];

7. 配置子路由
    const routes: Routes = [
      {path: 'xxx', children: [
        {path: 'aaa', component: AaaComponent},
        {path: '**', redirectTo: 'xxx'}
      ]},
      {path: '**', redirectTo: 'xxx'}
    ];

8. 
    Get传值, 在a标签中添加queryParams属性即可
    <a [routerLink]="[ '/xxx' ]" [queryParams]="{xx: 'xx'}">跳转xxx页面</a>
    
    接收时, 先导入 ActivatedRoute 并引用
        
        import {ActivatedRoute} from '@angular/router';

        constructor(public route: ActivatedRoute) {}

        this.route.queryParams.subscribe((data)=> {
            console.log(data);
        })

9. 动态路由
    配置: 
        const routes: Routes = [
          {path: 'xxx/:a', component: XxxComponent},
          {path: '**', redirectTo: 'xxx'}
        ];
    传值: 
        <a [routerLink]="[ '/xxx', 'xx' ]"></a>
    获取: 
        this.route.params.subscribe((data)=> {
            console.log(data);
        })

10. JS实现路由跳转
    1. 导入Router并引用
    2. this.router.navigate(['/xxx/']);
    如果要传值, 与配置路由时相同, 这种方式适用于普通路由和动态路由
    如果需要Get传值, 则需要导入 NavigationExtras

    let n: NavigationExtras = {
        queryParams: {'xxx': '123'}
    }
    this.router.navigate(['/xxx/'], n);

 

posted @ 2020-07-02 15:55  萌胖次  阅读(150)  评论(0编辑  收藏  举报