因工作需要學(xué)習(xí)angular ,特此總結(jié)一下~
一、angular安裝
1、安裝前準(zhǔn)備工作:
1.1、安裝 nodejs
安裝 angular 的計(jì)算機(jī)上面必須安裝最新的 nodejs--注意安裝 nodejs 穩(wěn)定版本
2、使用 npm/cnpm 命令安裝 angular/cli (只需要安裝一次)
npm install -g @angular/cli 或者 cnpm install -g @angular/cli
二、angular創(chuàng)建項(xiàng)目
1、ng new 項(xiàng)目名稱
例如 ng new angulardemo
如果要跳過(guò) npm i 安裝:
ng new angulardemo --skip-install

2、運(yùn)行項(xiàng)目
cd angulardemo
ng serve --open
3、目錄解構(gòu)分析

三、app.module.ts、組件分析
1、app.module.ts
Angular 應(yīng)用是模塊化的,它擁有自己的模塊化系統(tǒng),稱作 NgModule。 一個(gè) NgModule 就是一個(gè)容器,用于存放一些內(nèi)聚的代碼塊,這些代碼塊專注于某個(gè)應(yīng)用領(lǐng)域、某個(gè)工作流或一組緊密相關(guān)的功能。 它可以包含一些組件、服務(wù)提供商或其它代碼文件,其作用域由包含它們的 NgModule 定義。 它還可以導(dǎo)入一些由其它模塊中導(dǎo)出的功能,并導(dǎo)出一些指定的功能供其它 NgModule 使用。
/*這個(gè)文件是Angular 根模塊,告訴Angular如何組裝應(yīng)用*/
//BrowserModule,瀏覽器解析的模塊
import { BrowserModule } from '@angular/platform-browser';
//Angular核心模塊
import { NgModule } from '@angular/core';
//根組件
import { AppComponent } from './app.component';
import { NewsComponent } from './components/news/news.component';
import { HomeComponent } from './components/home/home.component';
import { HeaderComponent } from './components/header/header.component';
/*@NgModule裝飾器, @NgModule接受一個(gè)元數(shù)據(jù)對(duì)象,告訴 Angular 如何編譯和啟動(dòng)應(yīng)用*/
@NgModule({
declarations: [ /*配置當(dāng)前項(xiàng)目運(yùn)行的的組件*/
AppComponent, NewsComponent, HomeComponent, HeaderComponent
],
imports: [ /*配置當(dāng)前模塊運(yùn)行依賴的其他模塊*/
BrowserModule
],
providers: [], /*配置項(xiàng)目所需要的服務(wù)*/
bootstrap: [AppComponent] /* 指定應(yīng)用的主視圖(稱為根組件) 通過(guò)引導(dǎo)根AppModule來(lái)啟動(dòng)應(yīng)用 ,這里一般寫(xiě)的是根組件*/
})
//根模塊不需要導(dǎo)出任何東西, 因?yàn)槠渌M件不需要導(dǎo)入根模塊
export class AppModule { }
2、自定義組件
創(chuàng)建組件:
ng g component components/header
組件內(nèi)容解析
import { Component, OnInit } from '@angular/core'; /* 引入angular核心 */
@Component({
selector: 'app-header', /* 組件名稱 */
templateUrl: './header.component.html', /* html模版 */
styleUrls: ['./header.component.scss'] /* css樣式 */
})
export class HeaderComponent implements OnInit { /* 實(shí)現(xiàn)接口 */
constructor() { } /* 構(gòu)造函數(shù) */
ngOnInit() { /* 初始化加載時(shí)執(zhí)行的生命周期函數(shù) */
}
}
使用組件(在html文件中)
<app-header></app-header>
四、Angular 綁定數(shù)據(jù)
1、 數(shù)據(jù)文本綁定 {{ }}
<h1>
{{title}}
</h1>
<div>
1+1={{1+1}}
</div>
2、綁定 html
public content="<h2>我是一個(gè)html標(biāo)簽</h2>";
<div [innerHTML]="content"></div>
3.綁定屬性
<div [id]="id" [title]="msg">調(diào)試工具看看我的屬性</div>
4、數(shù)據(jù)循環(huán) *ngFor
(1) *ngFor 普通循環(huán)
public userlist:any[]=[{
username:'張三',
age:20
},{
username:'李四',
age:21
},
{
username:'王五',
age:40
}];
<ul>
<li *ngFor="let item of userlist">
{{item.username}}
</li>
</ul>
(2)循環(huán)的時(shí)候設(shè)置 key
<ul>
<li *ngFor="let item of userlist;let i = index;">
{{item.username}} --{{i}}
</li>
</ul>
5、條件判斷 *ngIf
<p *ngIf="userlist.length > 3">這是 ngIF 判斷是否顯示</p>
6、*ngSwitch
<ul [ngSwitch]="num">
<li *ngSwitchCase="1">ok</li>
<li *ngSwitchCase="2">未完成</li>
<li *ngSwitchCase="3">無(wú)效字段</li>
</ul>
7、執(zhí)行事件 (click)=”getData()”
<button class="button" (click)="getData()">
點(diǎn)擊按鈕觸發(fā)事件
</button>
<button class="button" (click)="setData()">
點(diǎn)擊按鈕設(shè)置數(shù)據(jù)
</button>
getData(){ /*自定義方法獲取數(shù)據(jù)*/
//獲取
alert(this.msg);
}
setData(){
//設(shè)置值
this.msg='這是設(shè)置的值';
}
8、表單事件
<input type="text" (keyup)="keyUpFn($event)"/>
keyUpFn(e){
console.log(e);
if(e.keyCode == 13){
console.log('11111')
};
}
9、雙向數(shù)據(jù)綁定
引入:FormsModule
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms'; //引入:FormsModule
@NgModule({
declarations: [
AppComponent,
],
imports: [
BrowserModule,
FormsModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
<input type="text" [(ngModel)]="inputValue"/>
{{inputValue}}
10、[ngClass]、[ngStyle]
(1)[ngClass]
<div [ngClass]="{'red': true, 'blue': false}">
這是一個(gè) div
</div>
public flag=false;
<div [ngClass]="{'red': flag, 'blue': !flag}">
這是一個(gè) div
</div>
public arr = [1, 3, 4, 5, 6];
<ul>
<li *ngFor="let item of arr, let i = index">
<span [ngClass]="{'red': i==0}">{{item}}</span>
</li>
</ul>
(2)[ngStyle]
public attr='red';
<div [ngStyle]="{'background-color':'green'}">你好 ngStyle</div>
<div [ngStyle]="{'background-color':attr}">你好 ngStyle</div>
11、管道[官方文檔]
public today=new Date();
<p>{{today | date:'yyyy-MM-dd HH:mm:ss' }}</p>
五、服務(wù)[官方文檔]
1.服務(wù)是一個(gè)廣義的概念,它包括應(yīng)用所需的任何值、函數(shù)或特性。狹義的服務(wù)是一個(gè)明確定義了用途的類。它應(yīng)該做一些具體的事,并做好。
2.Angular 把組件和服務(wù)區(qū)分開(kāi),以提高模塊性和復(fù)用性。 通過(guò)把組件中和視圖有關(guān)的功能與其他類型的處理分離開(kāi),你可以讓組件類更加精簡(jiǎn)、高效

1、創(chuàng)建服務(wù)
ng g service services/storage
2、app.module.ts 里面引入創(chuàng)建的服務(wù)
mport { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
//引入表單相關(guān)的模塊 才可以用雙休數(shù)據(jù)綁定
import { FormsModule } from '@angular/forms';
import { AppComponent } from './app.component';
//引入并且配置服務(wù)
import { StorageService } from './services/storage.service';
@NgModule({
declarations: [
AppComponent,
SearchComponent,
TodolistComponent
],
imports: [
BrowserModule,
FormsModule
],
providers: [StorageService], //NgModule 里面的 providers 里面依賴注入服務(wù)
bootstrap: [AppComponent]
})
export class AppModule { }
3、使用的頁(yè)面引入服務(wù),注冊(cè)服務(wù)
import { Component, OnInit } from '@angular/core';
//引入服務(wù)
import { StorageService } from '../../services/storage.service';
@Component({
selector: 'app-list',
templateUrl: './list.component.html',
styleUrls: ['./list.component.scss']
})
export class TodolistComponent implements OnInit {
constructor(public storage:StorageService) { //注冊(cè)服務(wù)
}
ngOnInit() {
}
}
4、使用
ngOnInit() {
var list:any=this.storage.get('tlist');
if(list){
this.list=list;
}
}
六、動(dòng)畫(huà)
(1)Angular 中的 dom 操作(原生 js)
ngAfterViewInit(){ //angular 中操作dom要在這個(gè)生命周期鉤子函數(shù)中
var boxDom:any=document.getElementById('box');
boxDom.style.color='red';
}
(2)Angular 中的 dom 操作(ViewChild)
<div #myBox>
我是一個(gè)dom節(jié)點(diǎn)
</div>
//在業(yè)務(wù)邏輯里面引入ViewChild
import { Component, OnInit,ViewChild} from '@angular/core';
@Component({
selector: 'app-news',
templateUrl: './news.component.html',
styleUrls: ['./news.component.scss']
})
export class NewsComponent implements OnInit {
//獲取dom節(jié)點(diǎn)
@ViewChild('myBox') myBox:any;
constructor() { }
ngOnInit() {
}
//ngAfterViewInit生命周期函數(shù)里面獲取dom
ngAfterViewInit(): void {
console.log(this.myBox.nativeElement);
this.myBox.nativeElement.style.width='100px';
this.myBox.nativeElement.style.height='100px';
this.myBox.nativeElement.style.background='red';
console.log(this.myBox.nativeElement.innerHTML);
}
}
補(bǔ)充: 父子組件中通過(guò) ViewChild 調(diào)用子組件的方法
(1)引入子組件
<app-header #header></app-header>
<button (click)="getChildRun()">獲取子組件的方法</button>
(2)關(guān)聯(lián)起來(lái)
import { Component, OnInit,ViewChild} from '@angular/core';
@Component({
selector: 'app-news',
templateUrl: './news.component.html',
styleUrls: ['./news.component.scss']
})
export class NewsComponent implements OnInit {
//獲取dom節(jié)點(diǎn)
@ViewChild('myBox') myBox:any;
//獲取一個(gè)組件
@ViewChild('header') header:any;
constructor() { }
ngOnInit() {
}
getChildRun(){
//調(diào)用子組件里面的方法
this.header.run();
}
}
七、Angular 父子組件以及組件之間通訊
1、父組件給子組件傳值-@input
(1)父組件調(diào)用子組件的時(shí)候傳入數(shù)據(jù)
<app-header [msg]="msg"></app-header>
(2)子組件引入 Input 模塊
import { Component, OnInit,Input} from '@angular/core';
(3)子組件中 @Input 接收父組件傳過(guò)來(lái)的數(shù)據(jù)
export class HeaderComponent implements OnInit {
@Input() msg:string
constructor() { }
ngOnInit() {
}
}
(4)子組件中使用父組件的數(shù)據(jù)
<h2>這是頭部組件--{{msg}}</h2>
2、子組件通過(guò)@Output 觸發(fā)父組件的方法
(1)子組件引入 Output 和 EventEmitter
import { Component, OnInit,Output,EventEmitter } from '@angular/core';
(2)子組件中實(shí)例化 EventEmitter
@Output() private outer=new EventEmitter<string>();
/*用 EventEmitter 和 output 裝飾器配合使用 <string>指定類型變量
(3)子組件通過(guò) EventEmitter 對(duì)象 outer 實(shí)例廣播數(shù)據(jù)
sendParent(){
// alert('zhixing');
this.outer.emit('msg from child')
}
(4).父組件調(diào)用子組件的時(shí)候,定義接收事件 , outer 就是子組件的 EventEmitter 對(duì)象 outer
<app-header (outer)="runParent($event)"></app-head
(5)父組件接收到數(shù)據(jù)會(huì)調(diào)用自己的 runParent 方法,這個(gè)時(shí)候就能拿到子組件的數(shù)據(jù)
//接收子組件傳遞過(guò)來(lái)的數(shù)據(jù)
runParent(msg:string){
console.log(msg);
}
八、Angular 中的生命周期函數(shù)
1、ngOnChanges()
當(dāng) Angular(重新)設(shè)置數(shù)據(jù)綁定輸入屬性時(shí)響應(yīng)。 該方法接受當(dāng)前和上一屬性值的 SimpleChanges 對(duì)象當(dāng)被綁定的輸入屬性的值發(fā)生變化時(shí)調(diào)用,首次調(diào)用一定會(huì)發(fā)生在 ngOnInit() 之前。
2、ngOnInit()
在 Angular 第一次顯示數(shù)據(jù)綁定和設(shè)置指令/組件的輸入屬性之后,初始化指令/組件。
在第一輪 ngOnChanges() 完成之后調(diào)用,只調(diào)用一次。
使用 ngOnInit() 有兩個(gè)原因:
1、在構(gòu)造函數(shù)之后馬上執(zhí)行復(fù)雜的初始化邏輯
2、在 Angular 設(shè)置完輸入屬性之后,對(duì)該組件進(jìn)行準(zhǔn)備。
有經(jīng)驗(yàn)的開(kāi)發(fā)者會(huì)認(rèn)同組件的構(gòu)建應(yīng)該很便宜和安全。
3、ngDoCheck()
檢測(cè),并在發(fā)生 Angular 無(wú)法或不愿意自己檢測(cè)的變化時(shí)作出反應(yīng)。在每個(gè) Angular 變更檢測(cè)周期中調(diào)用,ngOnChanges() 和 ngOnInit() 之后
4、ngAfterContentInit()
當(dāng)把內(nèi)容投影進(jìn)組件之后調(diào)用。第一次 ngDoCheck() 之后調(diào)用,只調(diào)用一次。
5、ngAfterContentChecked()
每次完成被投影組件內(nèi)容的變更檢測(cè)之后調(diào)用。ngAfterContentInit() 和每次 ngDoCheck() 之后調(diào)用。
6、ngAfterViewInit()
初始化完組件視圖及其子視圖之后調(diào)用。第 一次 ngAfterContentChecked() 之后調(diào)用,只調(diào)用一次。
7、ngAfterViewChecked()
每次做完組件視圖和子視圖的變更檢測(cè)之后調(diào)用。ngAfterViewInit()和每次 ngAfterContentChecked() 之后調(diào)用
8、ngOnDestroy()
當(dāng) Angular 每次銷毀指令/組件之前調(diào)用并清掃。在這兒反訂閱可觀察對(duì)象和分離事件處理器,以防內(nèi)存泄漏。在 Angular 銷毀指令/組件之前調(diào)用
import { Component,Input} from '@angular/core';
@Component({
selector: 'app-lifecycle',
templateUrl: './lifecycle.component.html',
styleUrls: ['./lifecycle.component.scss']
})
export class LifecycleComponent{
@Input('title') title:string;
public msg:string='我是一個(gè)生命周期演示';
public userinfo:string='';
public oldUserinfo:string='';
constructor() {
console.log('00構(gòu)造函數(shù)執(zhí)行了---除了使用簡(jiǎn)單的值對(duì)局部變量進(jìn)行初始化之外,什么都不應(yīng)該做')
}
ngOnChanges() {
console.log('01ngOnChages執(zhí)行了---當(dāng)被綁定的輸入屬性的值發(fā)生變化時(shí)調(diào)用(父子組件傳值的時(shí)候會(huì)觸發(fā))');
}
ngOnInit() {
console.log('02ngOnInit執(zhí)行了--- 請(qǐng)求數(shù)據(jù)一般放在這個(gè)里面');
}
ngDoCheck() {
//寫(xiě)一些自定義的操作
console.log('03ngDoCheck執(zhí)行了---檢測(cè),并在發(fā)生 Angular 無(wú)法或不愿意自己檢測(cè)的變化時(shí)作出反應(yīng)');
if(this.userinfo!==this.oldUserinfo){
console.log(`你從${this.oldUserinfo}改成${this.userinfo}`);
this.oldUserinfo = this.userinfo;
}else{
console.log("數(shù)據(jù)沒(méi)有變化");
}
}
ngAfterContentInit() {
console.log('04ngAfterContentInit執(zhí)行了---當(dāng)把內(nèi)容投影進(jìn)組件之后調(diào)用');
}
ngAfterContentChecked() {
console.log('05ngAfterContentChecked執(zhí)行了---每次完成被投影組件內(nèi)容的變更檢測(cè)之后調(diào)用');
}
ngAfterViewInit(): void {
console.log('06 ngAfterViewInit執(zhí)行了----初始化完組件視圖及其子視圖之后調(diào)用(dom操作放在這個(gè)里面)');
}
ngAfterViewChecked() {
console.log('07ngAfterViewChecked執(zhí)行了----每次做完組件視圖和子視圖的變更檢測(cè)之后調(diào)用');
}
ngOnDestroy() {
console.log('08ngOnDestroy執(zhí)行了····');
}
//自定義方法
changeMsg(){
this.msg="數(shù)據(jù)改變了";
}
}
運(yùn)行后結(jié)果:
再次進(jìn)入頁(yè)面:

只會(huì)執(zhí)行ngDoCheck() , ngAfterContentChecked() , ngAfterViewChecked()
九、Rxjs
它是一種針對(duì)異步數(shù)據(jù)流的編程。簡(jiǎn)單來(lái)說(shuō),它將一切數(shù)據(jù),包括 HTTP 請(qǐng)求,DOM 事件或者普通數(shù)據(jù)等包裝成流的形式,然后用強(qiáng)大豐富的操作符對(duì)流進(jìn)行處理,使你能以同步編程的方式處理異步數(shù)據(jù),并組合不同的操作符來(lái)輕松優(yōu)雅的實(shí)現(xiàn)你所需要的功能
1、RxJS 處理異步:
import {Observable} from 'rxjs';
let stream = new Observable(observer => {
setTimeout(() => {
observer.next('observable timeout');
}, 2000);
});
stream.subscribe(value => console.log(value));
從上面例子我們感覺(jué)Promise 和 RxJS 的用法基本相似。其實(shí)Rxjs相比Promise 要強(qiáng)大很多。
比如 Rxjs 中可以中途撤回、Rxjs 可以發(fā)射多個(gè)值、Rxjs 提供了多種工具函數(shù)等等。
2、Rxjs unsubscribe 取消訂閱
Promise 的創(chuàng)建之后,動(dòng)作是無(wú)法撤回的。
Observable 不一樣,動(dòng)作可以通過(guò)unsbscribe() 方法中途撤回,而且Observable 在內(nèi)部做了智能的處理.
Promise 創(chuàng)建之后動(dòng)作無(wú)法
let promise = new Promise(resolve => {
setTimeout(() => {
resolve('---promise timeout---');
}, 2000);
});
promise.then(value => console.log(value));
Rxjs 可以通過(guò) unsubscribe() 可以撤回 subscribe 的動(dòng)作
let stream = new Observable(observer => {
let timeout = setTimeout(() => {
clearTimeout(timeout);
observer.next('observable timeout');
}, 2000);
});
let disposable = stream.subscribe(value => console.log(value));
setTimeout(() => {
//取消執(zhí)行
disposable.unsubscribe();
}, 1000);
3、Rxjs 訂閱后多次執(zhí)行
我們想讓異步里面的方法多次執(zhí)行 , promise做不到
let promise = new Promise(resolve => {
setInterval(() => {
resolve('---promise setInterval---');
}, 2000);
});
promise.then(value => console.log(value));
但是Rxjs可以
let stream = new Observable<number>(observer => {
let count = 0;
setInterval(() => {
observer.next(count++);
}, 1000);
});
stream.subscribe(value => console.log("Observable>"+value));
4、使用 Rxjs 的工具函數(shù)map filter
import {Observable} from 'rxjs';
let stream= new Observable<any>(observer => {
let count = 0;
setInterval(() => {
observer.next(count++);
}, 1000);
});
stream.filter(val=>val%2==0)
.subscribe(value => console.log("filter>"+value));
stream
.map(value => {
return value * value
})
.subscribe(value => console.log("map>"+value));
5、Rxjs 延遲執(zhí)行
import {Observable,fromEvent} from 'rxjs';
import {map,filter,throttleTime} from 'rxjs/operators';
var button = document.querySelector('button');
fromEvent(button, 'click').pipe(
throttleTime(1000)
)
.subscribe(() => console.log(`Clicked`));
6、Rxjs6.x 的變化以及使用
RXJS6 改變了包的結(jié)構(gòu),主要變化在 import 方式和 operator 上面以及使用 pipe()
import {Observable} from 'rxjs';
import {map,filter} from 'rxjs/operators';
let stream= new Observable<any>(observer => {
let count = 0;
setInterval(() => {
observer.next(count++);
}, 1000);
});
stream.pipe(
filter(val=>val%2==0)
)
.subscribe(value => console.log("filter>"+value));
stream.pipe(
filter(val=>val%2==0), map(value => {
return value * value
})
)
.subscribe(value => console.log("map>"+value));?
十、Angular 中的數(shù)據(jù)交互
1、Angular get 請(qǐng)求數(shù)據(jù)
(1)在 app.module.ts 中引入 HttpClientModule 并注入
import {HttpClientModule} from '@angular/common/http';
imports: [
BrowserModule,
HttpClientModule
]
(2)在用到的地方引入 HttpClient 并在構(gòu)造函數(shù)聲明
import {HttpClient} from "@angular/common/http";
constructor(public http:HttpClient) { }
(3)get 請(qǐng)求數(shù)據(jù)
var api = "http://xxxxxxxxxxxx";
this.http.get(api).subscribe(response => {
console.log(response);
});
2、Angular post 提交數(shù)據(jù)
(1)在 app.module.ts 中引入 HttpClientModule 并注入
import {HttpClientModule} from '@angular/common/http';
imports: [
BrowserModule,
HttpClientModule
]
(2)在用到的地方引入 HttpClient、HttpHeaders 并在構(gòu)造函數(shù)聲明 HttpClient
import {HttpClient,HttpHeaders} from "@angular/common/http";
constructor(public http:HttpClient) { }
(3)post 提交數(shù)據(jù)
const httpOptions = {
headers: new HttpHeaders({ 'Content-Type': 'application/json' })
};
var api = "http://127.0.0.1:3000/doLogin";
this.http.post(api,{username:'張三',age:'20'},httpOptions).subscribe(response => {
console.log(response);
});
3、Angular Jsonp 請(qǐng)求數(shù)據(jù)
(1)在 app.module.ts 中引入 HttpClientModule、HttpClientJsonpModule 并注入
import {HttpClientModule,HttpClientJsonpModule} from '@angular/common/http';
imports: [
BrowserModule,
HttpClientModule,
HttpClientJsonpModule
]
(2)在用到的地方引入 HttpClient 并在構(gòu)造函數(shù)聲明
import {HttpClient} from "@angular/common/http";
constructor(public http:HttpClient) { }
(3)jsonp 請(qǐng)求數(shù)據(jù)
var api = "http://a.itying.com/api/productlist";
this.http.jsonp(api,'callback').subscribe(response => {
console.log(response);
});
4、Angular 中使用第三方模塊 axios 請(qǐng)求數(shù)據(jù)(無(wú)比懷念axios!?。。?!)
(1)安裝 axios
cnpm install axios --save
(2)用到的地方引入 axios
import axios from 'axios';
(3)用它
axios.get('/user?ID=12345')
.then(function (response) {
// handle success
console.log(response);
})
.catch(function (error) {
// handle error
console.log(error);
})
.then(function () {
// always executed
})
十一、路由
1、找到 app-routing.module.ts 配置路由
引入組件
import { HomeComponent } from './home/home.component';
import { NewsComponent } from './news/news.component';
import { NewscontentComponent } from './newscontent/newscontent.component';
配置路由
const routes: Routes = [
{path: 'home', component: HomeComponent},
{path: 'news', component: NewsComponent},
{path: 'newscontent/:id', component: NewscontentComponent},
{
path: '',
redirectTo: '/home',
pathMatch: 'full'
}
]
空路徑('')表示應(yīng)用的默認(rèn)路徑,當(dāng) URL 為空時(shí)就會(huì)訪問(wèn)那里,因此它通常會(huì)作為起點(diǎn)。 這個(gè)默認(rèn)路由會(huì)重定向到 URL /home,并顯示 HomeComponent。
找到 app.component.html 根組件模板,配置 router-outlet 顯示動(dòng)態(tài)加載的路由
<h1>
<a routerLink="/home">首頁(yè)</a>
<a routerLink="/news">新聞</a>
</h1>
<router-outlet></router-outlet>
2、**通配符
{ path: '**', component: PageNotFoundComponent }
最后一個(gè)路由中的 ** 路徑是一個(gè)通配符。當(dāng)所請(qǐng)求的 URL 不匹配前面定義的路由表中的任何路徑時(shí),路由器就會(huì)選擇此路由。 這個(gè)特性可用于顯示“404 - Not Found”頁(yè),或自動(dòng)重定向到其它路由。
3、routerLinkActive 設(shè) 置 routerLink 默認(rèn)選中路由
<h1>
<a [routerLink]="[ '/home' ]" routerLinkActive="active">首頁(yè)</a>
<a [routerLink]="[ '/news' ]" routerLinkActive="active">新聞</a>
</h1>
.active{
color:red;
}
4、動(dòng)態(tài)路由
配置動(dòng)態(tài)路由
const routes: Routes = [
{path: 'home', component: HomeComponent},
{path: 'news', component: NewsComponent},
{path: 'newscontent/:id', component: NewscontentComponent},
{
path: '',
redirectTo: '/home',
pathMatch: 'full'
}
];
跳轉(zhuǎn)傳值
<a [routerLink]="[ '/newscontent/',aid]">跳轉(zhuǎn)到詳情</a>
<a routerLink="/newscontent/{{aid}}">跳轉(zhuǎn)到詳情</a>
獲取動(dòng)態(tài)路由的值
import { ActivatedRoute} from '@angular/router';
constructor( private route: ActivatedRoute) { }
ngOnInit() {
console.log(this.route.params);
this.route.params.subscribe(data=>this.id=data.id);
}
5、動(dòng)態(tài)路由的 js 跳轉(zhuǎn)
引入
import { Router } from '@angular/router';
初始化
export class HomeComponent implements OnInit {
constructor(private router: Router) { }
ngOnInit() { }
goNews(){
// this.router.navigate(['/news', hero.id]);
this.router.navigate(['/news']);
//傳值
this.router.navigate(['/news', hero.id]);
}
}
6、路由 get 傳值 js 跳轉(zhuǎn)
引入 NavigationExtras
import { Router ,NavigationExtras} from '@angular/router';
定義一個(gè) goNewsContent 方法執(zhí)行跳轉(zhuǎn),用 NavigationExtras 配置傳參
goNewsContent(){
let navigationExtras: NavigationExtras = {
queryParams: { 'session_id': '123' },
fragment: 'anchor'
};
this.router.navigate(['/news'],navigationExtras);
}
獲取 get 傳值
constructor(private route: ActivatedRoute) {
console.log(this.route.queryParams);
}
7、父子路由
創(chuàng)建組件引入組件
import { NewsaddComponent } from './components/newsadd/newsadd.component';
import { NewslistComponent } from './components/newslist/newslist.component';
配置路由
{
path: 'news',
component:NewsComponent,
children: [
{
path:'newslist',
component:NewslistComponent
},
{
path:'newsadd',
component:NewsaddComponent
}
]
}
父組件中定義 router-outlet
<router-outlet></router-outlet>
十二、Angular 中自定義模塊
1、Angular 內(nèi)置模塊

2、Angular 自定義模塊
當(dāng)我們項(xiàng)目比較小的時(shí)候可以不用自定義模塊。但是當(dāng)我們項(xiàng)目非常龐大的時(shí)候把所有的組
件都掛載到根模塊里面不是特別合適。所以這個(gè)時(shí)候我們就可以自定義模塊來(lái)組織我們的項(xiàng)
目。并且通過(guò) Angular 自定義模塊可以實(shí)現(xiàn)路由的懶加載。
ng g module mymodule

創(chuàng)建模塊:
ng g module module/user --routing
ng g module module/article --routing
ng g module module/product --routing
創(chuàng)建組件:
ng g component module/user
ng g component module/user/components/profile
ng g component module/user/components/order
ng g component module/article
ng g component module/article/components/articlelist
ng g component module/article/components/info
ng g component module/product
ng g component module/product/components/plist
ng g component module/product/components/pinfo
配置懶加載
import { HomeComponent } from './components/home/home.component';
const routes: Routes = [
{
path:'',component : HomeComponent
},
{
path:'user',loadChildren : './usermodule/usermodule.module#UsermoduleModule'
}
];
最后我只想說(shuō)一句 vue相比于angular真的太簡(jiǎn)單了??!
以后在工作中遇到的問(wèn)題會(huì)持續(xù)更新在簡(jiǎn)書(shū)~
在學(xué)習(xí)angular的朋友一起共勉吧~~