淺談angular4,帶你入門

想學會angular4x建議看看這個https://segmentfault.com/a/1190000008754631入門教程,以下是工作中的總結:

、路由

1、Routes

路由配置,保存着哪個URL對應展示哪個組件,以及在哪個RouterOutlet中展示組件

2、RouterOutlet

在Html中標記路由內容呈現位置的佔位符指令

3、Router

負責在運行時執行路由的對象,可以通過調用其navigate()和navigateByUrl()方法來導航到一個指定的路由

4、RouterLink

在Html中聲明路由導航用的指令

5、ActivatedRoute

當前激活的路由對象,保存着當前路由的信息,如路由地址,路由參數等

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

snapshot --- 參數快照

subscribe ----參數訂閱

constructor(

    private route: ActivatedRoute,

    private router: Router,

   ) { }

第一種:查詢參數中

跳轉路由:

<a [routerLink]="['/product']" [queryParams]="{id:1}">商品</a>      ?問號;號

this.router.navigate(['login', 1],{ queryParams: { id: 1 } });

獲取參數

this.route.snapshot.queryParams["id"]

 

第二種:路由中

{ path: '/profile/:id', component: ProfileComponent }

獲取參數:

this.route.snapshot.params["id"]

this.router.params.subscribe((params:Params) => this.id = params.id);

1.以根路由跳轉/login

this.router.navigate(['login']);

2.設置relativeTo相對當前路由跳轉,route是ActivatedRoute的實例,使用需要導入ActivatedRoute

this.router.navigate(['login', 1],{relativeTo: route});

3.路由中傳參數 /login?name=1

this.router.navigate(['login', 1],{ queryParams: { name: 1 } });

4.preserveQueryParams默認值爲false,設爲true,保留之前路由中的查詢參數/login?name=1 to /home?name=1

this.router.navigate(['home'], { preserveQueryParams: true });

5.路由中錨點跳轉 /home#top

this.router.navigate(['home'],{ fragment: 'top' });

6.preserveFragment默認爲false,設爲true,保留之前路由中的錨點/home#top to /role#top

this.router.navigate(['/role'], { preserveFragment: true });

7.skipLocationChange默認爲false,設爲true,路由跳轉時瀏覽器中的url會保持不變,但是傳入的參數依然有效

this.router.navigate(['/home'], { skipLocationChange: true });

8.replaceUrl默認爲true,設爲false,路由不會進行跳轉

this.router.navigate(['/home'], { replaceUrl: true });

  ###輔助路由

插座 outlet

思路:

  1、在APP組件的模板上再定義一個插座來顯示聊天面板

  2、單獨開發一個聊天室組件,只顯示在新定義的插座上

  3、通過路由參數控制新插座是否顯示聊天面板

 

###路由守衛

CanActive : 處理導航到某路由的情況

CanActivateChild:處理導航到某子路由的情況

CanDeactivate:處理從當前路由離開的情況

Resolve:在路由激活之前獲取路由數據

CanLoad:處理異步導航到某特性模塊的情況

注意事項

1、 <base> 標籤添加到我們的 index.html 文件

2、根模塊中使用 forRoot(),子模塊中使用 forChild()

3、使用一個名爲 router-outlet 的指令告訴 Angular 在哪裏加載組件

4、動態路由 { path: '/profile/:username', component: ProfileComponent }

另一個很有用的路由功能是 component-less 路由

https://segmentfault.com/a/1190000009265310

  1. 使用 component-less 路由允許我們將路由組合在一起,並讓它們共享路由配置信息和 outlet。
  2. 需要注意的是,我們沒有將 SettingsModule 導入到我們的 AppModule 中,而是通過 loadChildren 屬性,告訴 Angular 路由依據 loadChildren 屬性配置的路徑去加載 SettingsModule 模塊。這就是模塊懶加載功能的具體應用,當用戶訪問 /settings/** 路徑的時候,纔會加載對應的 SettingsModule 模塊,這減少了應用啓動時加載資源的大小。

數據綁定:

 

 

output:

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章