angularcli 第八篇(router 路由)


更多詳細:https://segmentfault.com/a/1190000009265310

 

一、標題:頁面有兩個按鈕(test1、test2),點擊這兩個按鈕,跳轉相應頁面~

注:可直接創建一個帶路由模塊的項目:ng new project --routing   (下面針對新建項目時沒有帶路由,后邊再來新建路由)

 

1、新建兩個頁面 test1、test2(html、css、ts):      ng g component test1  

 

在app.modules.ts(模塊)中:

(1)導入根組件,以及相應子組件(test1、test2)   

(2)添加相應路由組件 import { AppRoutingModules } from "./app/routing";

(3)初始化路由器imports: [ RouterModule.forRoot(routes) ],用於在主模塊中定義主要的路由信息

 

 

2、在app.component.html中添加相應的跳轉按鈕,以及路由路徑

 

3、路由配置:新建路由模塊 app.routing.ts(配置文件)      ng generate module app-routing --flat --module=app

    • import 根組件、子組件、路由組件;
    • 編寫路由路徑 const routes;
方法:
const
routes: Routes = [ // path:路徑 component:組件 { path: 'news', component: Newsomponent },
{ path: 'detail/:id', component: DetailComponent }, // 帶參數 { path: 'other', loadChildren:"./other/other.module#otherModule" },// 懶加載子模塊, 子模塊需要配置路由設置啟動子組件
  { path: '**', pathMatch: 'full', redirectTo: '' } // 重定向 
];

 

/index設置頁面下有 /index/testUrl1 和  /index/testUrl2 兩個頁面,分別表示個人資料頁和修改密碼頁。

我們可能希望我們的 / settings 頁面擁有自己的組件,然后在設置頁面組件中顯示 / settings/profile 和 / settings/password 頁面。我們可以這樣做:

在這里,我們在 setttings 路由中定義了兩個子路由,它們將繼承父路由的路徑,因此修改密碼頁面的路由匹配地址是 /settings/password ,依此類推。

接下來,我們需要在我們的 AppComponent(index) 組件中添加 router-outlet 指令,因為我們要在設置頁面中呈現子路由。

 

二、鏈接及訪問

<a routerLink="/detail/test1" routerLinkActive="active">detail</a>
<a [routerLink]="['/detail', news.id]">{{news.title}}</a>   //路由中傳參數
<a [routerLink]="[{ outlets: { let2: ['news'] } }]">Contact</a>

//注:routerLinkActive="active"
 即在本路由激活時添加樣式 .active

 

import { Router } from '@angular/router';
// ...
constructor(private router: Router) {}

// ...
 to_detail(item){
  this.router.navigate(['/detail', {queryParams:item}]); //路由中傳參數(多個參數)
  this.router.navigate({'
/detail',news.id}); //一個參數   
this.router.navigate([{ outlets: { let2: null }}]);
}

注:navigateByUrl 方法指向完整的絕對路徑

 

 

傳參之后的接收方法:

1.snapshot
import { ActivateRoute } from '@angular/router';

constructor( public route: ActivateRoute ) { };
ngOnInit(){
    this.data = this.route.snapshot.params['id'];
};
 
2.queryParams
import { ActivateRoute } from '@angular/router';

constructor( public activeRoute:ActivateRoute ) { };
ngOnInit(){
  this.activeRoute.queryParams.subscribe(params => {
    console.log(params);
  });
};

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM