angular中路由的使用

1、路由的基本使用

  • 一、建立兩個組件html

    ng g c components/home
    ng g c components/news
    複製代碼
  • 二、在app-routing.module.ts中配置路由git

    const routes: Routes = [
      // 默認訪問地址
      {
        path: '',
        redirectTo: 'home',
        pathMatch: 'full'
      },
      {
        path: 'home',
        component: HomeComponent
      },
      {
        path: 'news',
        component: NewsComponent
      },
      // 當沒有匹配的時候就到home路由
      {
        path: '**',
        redirectTo: 'home',
        pathMatch: 'full'
      }
    ];
    複製代碼
  • 三、使用路由跳轉shell

    <ul>
      <li>
        <a routerLink="home">首頁</a>
      </li>
      <li>
        <a routerLink="news">新聞</a>
      </li>
    </ul>
    <!-- 路由切換的槽 -->
    <router-outlet></router-outlet>
    複製代碼

2、幾種路由跳轉的方式

  • 一、方式一直接使用bootstrap

    <a routerLink="home">首頁</a>
    複製代碼
  • 二、動態傳遞值的方式bash

    <a [routerLink]="[ '/home' ]">首頁</a>
    複製代碼

3、路由選中的樣式

<a routerLink="home" routerLinkActive="active">首頁</a>
複製代碼

4、動態路由

  • 一、配置路由文件app

    ...
    {
      path: 'news',
      component: NewsComponent
    },
    {
      path: 'news/:id',
      component: DetailComponent
    },
    ...
    複製代碼
  • 二、配置路由的跳轉ide

    <ul>
      <li *ngFor="let item of articleList">
        <a [routerLink]="['/news', item.id]">{{item.title}}</a>
        <!-- <a routerLink="/news/{{item.id}}">跳轉到詳情</a> -->
      </li>
    </ul>
    複製代碼
  • 三、獲取動態路由傳遞過來的值ui

    import { ActivatedRoute } from '@angular/router';
    ...
    private sub: any;
      constructor(private readonly route: ActivatedRoute) {}
    
      ngOnInit() {
        console.log(this.route);
        this.sub = this.route.params.subscribe((params: any) => {
          console.log(params);
        });
        // 或者使用snapshot是路由的一個快照【id爲你寫的動態路由的】
        console.log(this.route.snapshot.paramMap.get('id'));
      }
      ngOnDestroy() {
        this.sub.unsubscribe();
      }
    }
    複製代碼

5、使用query傳遞參數

  • 一、路由跳轉的時候this

    <a [routerLink]="['news']" [queryParams]="{ id: 1, name: 'hello', age: 20 }" routerLinkActive="active" >新聞</a >
    複製代碼
  • 二、組件中獲取路由參數spa

    import { ActivatedRoute } from '@angular/router';
    
    export class NewsComponent implements OnInit, OnDestroy {
      public sub: any;
      constructor(private readonly route: ActivatedRoute) {}
    
      ngOnInit() {
        this.sub = this.route.queryParams.subscribe(data => {
          console.log(data);
        });
      }
    
      ngOnDestroy() {
        this.sub.unsubscribe();
      }
    }
    複製代碼

6、在js中路由跳轉

  • 一、不帶參數的跳轉

    import { Router } from '@angular/router';
    
    export class DetailComponent implements OnInit, OnDestroy {
      private sub: any;
      constructor(private readonly router: Router) {}
    
      public goHome() {
        this.router.navigate(['/home']);
      }
    }
    複製代碼
  • 二、帶參數的跳轉(動態路由的方式)

    import { ActivatedRoute, Router } from '@angular/router';
    
    export class NewsComponent implements OnInit, OnDestroy {
      constructor(private readonly router: Router) {}
      public detail(): void {
        this.router.navigate(['/news', '2']);
      }
    }
    複製代碼
  • 三、帶query參數的跳轉

    import { ActivatedRoute, Router, NavigationExtras } from '@angular/router';
    
    ...
    public goHome() {
      const navigationExtras: NavigationExtras = {
        // query參數
        queryParams: {
          name: 'hello',
          age: 20
        },
        fragment: 'aaa' // 錨點
      };
      this.router.navigate(['/home'], navigationExtras);
    }
    複製代碼

7、路由的嵌套

  • 一、配置路由

    const routes: Routes = [
      {
        path: 'home',
        component: HomeComponent,
        children: [
          {
            path: 'add',
            component: AddComponent
          },
          {
            path: 'edit',
            component: EditComponent
          }
        ]
      },
      ...
    ]
    複製代碼
  • 二、配置路由的跳轉

    <p>
      <a [routerLink]="['/home/add']" routerLinkActive="active">添加內容</a>
    </p>
    <p>
      <a [routerLink]="['/home/edit']" routerLinkActive="active">編輯內容</a>
    </p>
    複製代碼

8、路由與懶加載模塊

  • 一、建立兩個module和對應的組件

    ng g m pages/home --routing # 建立帶路由的模塊
    ng g m pages/user --routing
     # 建立組件
    ng g c pages/home
    ng g c pages/user
    ng g c pages/user/login
    ng g c pages/user/components/login
    ng g c pages/user/components/infomation
    複製代碼
  • 二、主路由

    const routes: Routes = [
      {
        path: '',
        redirectTo: 'home',
        pathMatch: 'full'
      },
      {
        path: 'home',
        loadChildren: './pages/home/home.module#HomeModule'
      },
      {
        path: 'userInfo',
        loadChildren: './pages/user/user.module#UserModule'
      },
      {
        path: '**',
        loadChildren: './pages/home/home.module#HomeModule'
      }
    ];
    複製代碼
  • 二、home的路由

    const routes: Routes = [
      {
        path: '',
        redirectTo: 'index',
        pathMatch: 'full'
      },
      {
        path: 'index',
        component: HomeComponent
      },
      {
        path: '**',
        redirectTo: 'index',
        pathMatch: 'full'
      }
    ];
    複製代碼
  • 三、用戶的路由

    const routes: Routes = [
      {
        path: '',
        redirectTo: 'user',
        pathMatch: 'full'
      },
      {
        path: 'user',
        component: UserComponent,
        children: [
          {
            path: 'login',
            component: LoginComponent
          },
          {
            path: 'user_info',
            component: InfomationComponent
          }
        ]
      },
      {
        path: '**',
        redirectTo: 'user',
        pathMatch: 'full'
      }
    ];
    複製代碼

9、模塊的預加載

上面對模塊進行了懶加載,那麼進入頁面後不會所有加載出來,須要用戶點擊當頁面後纔會加載當前的數據,可是這樣每每有個弊端(有些數據一開始是沒有的,須要等待下才會出現)。爲了解決這個等待,咱們能夠進行預加載

  • 一、方式1、簡單粗暴的方法(直接在根路由下使用PreloadAllModules默認是NoPreloading)

    import { Routes, RouterModule, PreloadAllModules } from '@angular/router';
    
    @NgModule({
      imports: [
        RouterModule.forRoot(routes, { preloadingStrategy: PreloadAllModules })
      ],
      exports: [RouterModule]
    })
    export class AppRoutingModule {}
    複製代碼
  • 二、方式2、根據本身配置去預加載對應的模塊

    • 配置本身須要預加載的路由

      const routes: Routes = [
        {
          path: 'home',
          loadChildren: './pages/home/home.module#HomeModule',
          data: { preload: true }
        },
        {
          path: 'userInfo',
          loadChildren: './pages/user/user.module#UserModule',
          data: { preload: true }
        }
      ];
      複製代碼
    • 本身建立一個my-preloading-strategy.ts

      import { Route, PreloadingStrategy } from '@angular/router';
      import { Observable, of } from 'rxjs';
      
      export class MyPreloadingStrategy implements PreloadingStrategy {
        preload(route: Route, fn: () => Observable<any>): Observable<any> {
          return route.data && route.data.preload ? fn() : of(null);
        }
      }
      複製代碼
    • 三、在根模塊中注入服務中

      import { MyPreloadingStrategy } from './common/my-preloading-strategy';
      
      /* @NgModule接受一個元數據對象,告訴angular如何編譯和啓動應用 */
      @NgModule({
        declarations: [AppComponent], // 引入當前項目運行的組件、指令、管道
        imports: [BrowserModule, AppRoutingModule, HomeModule, UserModule], // 引入當前模塊運行依賴別的模塊
        exports: [], // 對外暴露出去的
        providers: [MyPreloadingStrategy], // 定義的服務
        bootstrap: [AppComponent] // 指定應用的主視圖
      })
      export class AppModule {}
      複製代碼
    • 四、在根路由中使用

      @NgModule({
        imports: [
          RouterModule.forRoot(routes, {
            preloadingStrategy: MyPreloadingStrategy
          })
        ],
        exports: [RouterModule]
      })
      export class AppRoutingModule {}
      複製代碼

10、使用Location模塊返回到上一個菜單

  • 一、導包

    import { Location } from '@angular/common'
    複製代碼
  • 二、使用

    // 返回上一級菜單
    private goback(): void {
      this.location.back();
    }
    複製代碼

11、代碼下載地址

相關文章
相關標籤/搜索