angular 路由 Router

1、Routers(路由配置),接收一個路由配置數組。

屬性html

  • path : 一個字符串用來匹配DSL
  • patchMatch : 指定匹配策略
  • component : 組件名
  • redirectTo : 路由重定位
  • outlet : 將組件放置在視圖中指定outlet中。
  • canActivate : 一組DI令牌,用來查找CanActivate處理器。
  • canActivateChild : 一組DI令牌,用來查找CanActivateChild處理器。
  • canDeactivate : 一組DI令牌,用來查找CanDeactivate處理器。
  • data : 經過ActivateRoute向組件傳遞額外的數據。
  • resolve : 一組DI令牌,用來查找Resolve處理器。
  • loadChildren:子菜單鏈接的路由配置文件
  • children : 一組子路由定義

實例:
app-routing.module.ts配置:數組

const AppRoutes: Routes = [
    {path: '', redirectTo: '/app/dashboard', pathMatch: 'full'},//頁面啓動首頁顯示
    {path: 'app', component: LayoutComponent},
    {path: 'demoHouseList', component: HouseListComponent},
    {path: 'houseMarket', loadChildren: './house-market/houseMarket.module#HouseMarketModule'}//houseMarket後面還要子菜單,在houseMarket-routing.module配置中

houseMarket-routing.module.ts配置:angular2

const Routing: Routes = [
  {
    path: '',
    component: HouseMarketComponent,
    children: [
      {path: 'list', component: ListComponent},
      {path: 'search', component: SearchComponent}
    ]
  }
];

頁面訪問:
首頁啓動路徑:http://localhost:4200/#/app/dashboard
內頁:http://localhost:4200/#/houseMarket/listapp

2、指令

RouterOutlet--至關於一個佔位符,在Angular中根據路由狀態動態插入視圖。this

如何使用url

<router-outlet></router-outlet>
<router-outlet name='left'></router-outlet>
<router-outlet name='right'></router-outlet>

一個路由插座能夠在任什麼時候候組件實例化時發出一個activate消息,而且在組件銷燬時發出一個deactivate消息。debug

<router-outlet (activate)="onActivate($event)" (deactivate)="onDeactivate($event)"></route-outlet>

RouterLink指令可以連接到應用中指定區域。若是使用靜態連接,能夠像下面這樣直接使用:code

<a routerLink='/user'>link to user component</a>

若是是動態生成的連接,能夠傳遞一個數組帶有路徑片斷,以及後續每個參數的片斷。
例如 ['/team', teamId, 'user', userName, {details:true}],表示咱們想要連接到地址 /team/11/user/bob;details=truecomponent

多個靜態片斷能夠合併到一個(示例:['/team/11/user'], username, {details: true})router

第一個片斷名可使用/, ./, 或者 ../ 開關:

  • 若是片斷以 / 開始,路由器會以應用的根路由查找起點
  • 若是片斷以 ./ 開始,或者不以斜線開始中,路由器會從當前路由的子節點路徑開始查找
  • 若是片斷以 ../ 路由會從上一級節點爲查詢路徑

使用如下方式設置查詢參數和片斷

<a [routerLink]="['/user/bob']" [queryParams]="{debug: true}" fragment="education">link to user component</a>

這會生成連接 /user/bob#education?debug=true

3、接口

ActivatedRoute(當前激活路由對象,主要用於保存路由,獲取路由傳遞的參數。)

如何使用

@Component({templateUrl:'./my-component.html'})
    class MyComponent {
      constructor(**route: ActivatedRoute**) {
        const id: Observable<string> = route.params.map(p => p.id);
        const url: Observable<string> = route.url.map(s => s.join(''));
        const user = route.data.map(d => d.user); //includes `data` and `resolve`
      }
    }

類定義

interface ActivatedRoute {
      snapshot : ActivatedRouteSnapshot
      url : Observable<UrlSegment[]>
      params : Observable<Params>
      queryParams : Observable<Params>
      fragment : Observable<string>
      data : Observable<Data>
      outlet : string
      component : Type<any>|string
      routeConfig : Route
      root : ActivatedRoute
      parent : ActivatedRoute
      firstChild : ActivatedRoute
      children : ActivatedRoute[]
      pathFromRoot : ActivatedRoute[]
      toString() : string
    }

屬性

  • snapshot : ActivatedRouteSnapshot 當前路由快照
  • url : Observable<urlsegment[]> 當前路由匹配的URL片斷。
  • params : Observable<Params> 當前路由的矩陣參數
  • queryParams : Observable<Params> 全部路由共享的查詢參數
  • fragment : Observable<string> 全部路由共享的URL片斷
  • data :Observable<Data> 當前路由的靜態或者動態解析的數據
  • outlet: string 當前路由插座的名稱。一個常量值。
  • component : Type<any>|string 路由對應的組件。一個常量值。
  • routeConfig : Route 當前路由狀態樹的根節點
  • root : ActivatedRoute 根路由
  • parent : ActivatedRoute 當前路由在狀態樹中的父節點
  • firstChild: ActivatedRoute 當前路由的第一個子節點
  • children : ActivatedRoute 當前路由在路由狀態樹中的全部子節點
  • pathFromRoot : ActivatedRoute 根節點到當前節點的路徑
  • toString() : string

傳遞參數方式,以及ActivatedRoute獲取他們的方式

一、在查詢參數中傳遞數據:

/product?id=1&name=2 //傳參
=>ActivatedRoute.queryParams[id] //獲取參數

二、在路由路徑中傳遞數據:

{path:'/product/:id'} //路由配置
=>/product/1 //路由顯示方式
=>ActivatedRoute.params[id] //獲取參數

三、在路由配置中傳遞數據

{path:'/product',component:ProductComponent,data:[{isProd:true}]} //路由配置
=>ActivatedRoute.data0 //獲取參數

接收參數:

import {ActivatedRoute , Router} from '@angular/router';
export class HousedetailComponent implements OnInit {
    houseMarketId: any;
    constructor(private route: ActivatedRoute){}
    ngOnInit() {
            
        this.houseMarketId = this.route.snapshot.params('id');或
        this.houseMarketId = this.route.snapshot.paramMap.get('id');
    }
}

現已list列表頁點擊跳轉到詳情頁來實例ActivatedRoute用法:

在路由路徑中傳遞數據:{path: 'detail/:id', component: detailComponent}

1、list.component.ts和detail.component.ts文件都引入

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

2、list.component.ts中的點擊事件:

goDetail(houseMarketId) {
    const url = '/detail/' + houseMarketId;
    let queryParams;
    queryParams = {source: 'list'};
    this.router.navigate([url], {relativeTo: this.route, queryParams: queryParams});
  }

訪問路徑:http://localhost:400/detail/e028606e317c11e896ef7cd30adbbf4c?source=list

3、detail.component.ts在初始化時,取的url路由帶過來的id值,來取該id對應信息,即:this.route.snapshot.paramMap.get('id')

ngOnInit() {
    this.houseMarketId = this.route.snapshot.paramMap.get('id');
    this.housedetailService.getById(this.houseMarketId, this.userId ? this.userId : '')
      .then((data) => {
        if (data.code === 200) {
          this.houseMarket = data.data;
        }
      });
}

參考:https://www.kancloud.cn/wujie...

相關文章
相關標籤/搜索