一、序章
關(guān)于Angular版本稽煤,Angular官方已經(jīng)統(tǒng)一命名Angular 1.x統(tǒng)稱為Angular JS;Angular 2.x及以上統(tǒng)稱Angular
- 后續(xù)練習(xí)的源碼地址都會(huì)上傳到github庫(kù)上败潦,源碼下載地址
回顧前端框架學(xué)習(xí)歷程
最早開(kāi)始是對(duì)Angular JS比較熟悉啃擦,2015年那時(shí)候部門(mén)選擇了比較熱門(mén)的Angular JS結(jié)合ionic1.x加上codova平臺(tái)進(jìn)行混合式的webAPP開(kāi)發(fā),那時(shí)候用Angular JS開(kāi)發(fā)過(guò)挺多項(xiàng)目的撤缴,到如今也還有一些基于Angular JS的老項(xiàng)目在迭代開(kāi)發(fā)和維護(hù)东揣,但是存在一個(gè)問(wèn)題就是現(xiàn)在很多人不會(huì)愿意再去學(xué)習(xí)舊版本的Angular JS了,因?yàn)楣雀枭?jí)發(fā)布的Angular可以說(shuō)是一個(gè)大的跨度腹泌,他們并不是版本迭代升級(jí)這么簡(jiǎn)單嘶卧,你甚至可以完全把他們當(dāng)做2個(gè)不同的框架進(jìn)行學(xué)習(xí),這也導(dǎo)致了之前的一部分Angular JS流量轉(zhuǎn)向了另外2大框架vue和react凉袱,同樣我們部門(mén)后續(xù)的主流技術(shù)棧也是轉(zhuǎn)向了vue和react芥吟。為什么要花時(shí)間去學(xué)習(xí)Angular?
Angular還是有很多的公司在使用专甩,這也是我打算花點(diǎn)時(shí)間從新入門(mén)Angular4.x版本的原因钟鸵,同時(shí)Angular一直都是一個(gè)很熱門(mén)的前端框架,并不是說(shuō)它已經(jīng)過(guò)時(shí)了(當(dāng)然Angular JS是真的過(guò)時(shí)了)涤躲,作為前端目前最流行的三大框架之一棺耍,還是值得花費(fèi)一些時(shí)間去學(xué)習(xí)參考一下的。為什么選擇Angular4.x版本作為入門(mén)學(xué)習(xí)种樱?
在選擇Angular版本的時(shí)候我思考了挺多蒙袍,最后決定從Angular4.x快速入門(mén)寫(xiě)起俊卤。為什么會(huì)選擇Angular4.x版本進(jìn)行入門(mén)的學(xué)習(xí)呢?原因在于害幅,之前一直在做vue和react的項(xiàng)目對(duì)Angular的學(xué)習(xí)還停留在以前的Angular JS消恍,只是對(duì)后續(xù)Angular發(fā)布的版本保持著一定的關(guān)注,了解一些Angular相關(guān)的以现,知道Angular的版本迭代更新比較頻繁狠怨,到目前最新的正式版本已經(jīng)迭代到7.x了,8.0的beta版本也已經(jīng)發(fā)布邑遏,那給我的版本入門(mén)選擇也就比較多了佣赖。一開(kāi)始我的打算是既然要學(xué)就學(xué)習(xí)最新的版本從7.x開(kāi)始,后續(xù)我經(jīng)過(guò)一些綜合的考慮放棄了7.x版本選擇了4.x版本作為入門(mén)记盒,Angular4.x作為入門(mén)是比較合適的茵汰,Angular從1.x之后的版本迭代都是向下兼容,那4.x作為一個(gè)承上啟下的版本選擇它無(wú)疑是最合適的孽鸡,可提供參考的社區(qū)資料也會(huì)更完善一些蹂午。后續(xù)我比較期待Angular8.0.0版本的發(fā)布,只因?yàn)樗鼘⒄桨琁vy Renderer 彬碱,對(duì)于Angular Ivy的了解可以參考這2篇博客進(jìn)行理解 Ivy-Angular下一代渲染引擎 和 如何評(píng)價(jià) Angular 的新Ivy Render豆胸。-
快速入門(mén)從哪些方面開(kāi)始?
個(gè)人總結(jié)出來(lái)的一些經(jīng)驗(yàn)巷疼,怎樣以高效的方式入門(mén)學(xué)習(xí)一門(mén)新的前端框架晚胡,后續(xù)的快速入門(mén)我準(zhǔn)備從以下幾個(gè)模塊開(kāi)始:- 環(huán)境搭建
- 路由跳轉(zhuǎn)
- 頁(yè)面?zhèn)鲄⒓敖涌谡?qǐng)求
- 組件
- 其它
一、環(huán)境搭建
基礎(chǔ)要求
開(kāi)發(fā)環(huán)境配置方式
1. 通過(guò)git clone模板
- 通過(guò)git克隆官方快速入門(mén)模板估盘,打開(kāi)終端執(zhí)行命令git clone https://github.com/angular/quickstart
- 用IDE打開(kāi)克隆下來(lái)的工程,我用的是webstorm骡尽,然后安裝依賴遣妥,在當(dāng)前工程目錄下執(zhí)行npm install
- 依賴下載安裝完成后直接npm start運(yùn)行
2.通過(guò)Angular CLI腳手架安裝
二、路由跳轉(zhuǎn)
- app.modules.ts中需要導(dǎo)入路由模塊
import { RouterModule } from '@angular/router';
@NgModule({
imports: [BrowserModule, FormsModule, HttpModule, RouterModule],
declarations: [AppComponent, UserComponent],
bootstrap: [AppComponent]
})
export class AppModule { }
- 在app.modules.ts中配置路由信息
import { Routes, RouterModule } from '@angular/router';
import { UserComponent } from './user.component';
export const ROUTES: Routes = [
{ path: 'user', component: UserComponent }
];
@NgModule({
imports: [
BrowserModule,
RouterModule.forRoot(ROUTES)
],
// ...
})
export class AppModule {}
- 父子路由配置children和loadChildren懶加載
// children(父子路由配置)
// 訪問(wèn)/tabs跳轉(zhuǎn)到TabsPage攀细,TabsPage只是一個(gè)底部導(dǎo)航箫踩。也相當(dāng)于web網(wǎng)站的頂部導(dǎo)航或左側(cè)導(dǎo)航
// 所以需要訪問(wèn)/tabs/demo,才會(huì)顯示導(dǎo)航和內(nèi)容
// 訪問(wèn)/tabs/tab1/test谭贪,顯示導(dǎo)航和testPage境钟,test模塊使用loadChildren懶加載
{
path: 'tabs',
component: TabsPage,
children: [
{path: 'demo', component: DemoPage},
{path: 'tab1', component: Tab1Page},
{path: 'tab1/test', loadChildren: './pages/tab1/test/test.module#TestPageModule'},
]
}
- routerLink
為了讓我們鏈接到已設(shè)置的路由,我們需要使用 routerLink 指令俭识,具體示例如下:
<nav>
<a routerLink="/">Home</a>
<a routerLink="/settings/password">Change password</a>
<a routerLink="/settings/profile">Profile Settings</a>
</nav>
當(dāng)我們點(diǎn)擊以上的任意鏈接時(shí)慨削,頁(yè)面不會(huì)被重新加載。反之,我們的路徑將在 URL 地址欄中顯示缚态,隨后進(jìn)行后續(xù)視圖更新磁椒,以匹配 routerLink 中設(shè)置的值。
- app.component.ts主頁(yè)中配置路由導(dǎo)航頁(yè)面
import { Component } from '@angular/core';
@Component({
selector: 'my-app',
template: `<div class="app">
<h1>歡迎來(lái)到Angular的世界</h1>
<nav>
<a routerLink="/user">我的</a>
</nav>
<router-outlet></router-outlet>
</div>`,
})
export class AppComponent { }
- user.component.ts用戶組件模塊中代碼
import { Component } from '@angular/core';
interface Address {
province: string;
city: string;
}
@Component({
selector: 'sl-user',
template: `
<h2>大家好猿规,我是{{name}}</h2>
<p>我來(lái)自<strong>{{address.province}}</strong>省,
<strong>{{address.city}}</strong>市
</p>
<button (click)="toggleSkills()">
{{ showSkills ? "隱藏技能" : "顯示技能" }}
</button>
<div *ngIf="showSkills">
<h3>我的技能</h3>
<ul>
<li *ngFor="let skill of skills">
{{skill}}
</li>
</ul>
<form (submit)="addSkill(skill.value)">
<label>添加技能</label>
<input type="text" #skill>
</form>
</div>
`
})
export class UserComponent {
name: string;
address: Address;
showSkills: boolean;
skills: string[];
constructor() {
this.name = 'liangyu';
this.address = {
province: '湖南',
city: '永州'
};
this.showSkills = true;
this.skills = ['AngularJS 1.x', 'Angular 2.x', 'Angular 4.x'];
}
toggleSkills() {
this.showSkills = !this.showSkills;
}
addSkill(skill: string) {
let skillStr = skill.trim();
if (this.skills.indexOf(skillStr) === -1) {
this.skills.push(skillStr);
}
}
}
三、頁(yè)面跳轉(zhuǎn)傳參&接口請(qǐng)求
3.1宙橱、通過(guò)routerLink傳參方式
- 通過(guò)動(dòng)態(tài)路由進(jìn)行參數(shù)傳遞,app.module.ts在path路徑后面通過(guò)":"拼接需要傳遞的參數(shù)
export const ROUTES: Routes = [
{ path: '', pathMatch: 'full', redirectTo: '/' },
{ path: 'user/:name', component: UserComponent },
];
- app.component.ts中的跳轉(zhuǎn)鏈接
<a [routerLink]="['/user', '涼雨啊']">我的</a>
<!--或者方式2-->
<!--<a [routerLink]="['/user']" [queryParams]="{name:'涼雨啊'}">我的</a>-->
- userComponent.ts中接收姨俩,需要導(dǎo)入import { ActivatedRoute } from '@angular/router';
// 獲取參數(shù)值
this.name = this.routeInfo.snapshot.params['name'];
// 接收方式2傳遞的值
// this.name = this.routeInfo.snapshot.queryParams['name'];
console.log(this.name)
3.2、通過(guò)Router API中的navigate() 方法跳轉(zhuǎn)路由傳參
- app.module.ts配置路由
{ path: 'user', component: UserComponent },
- 在需要跳轉(zhuǎn)的導(dǎo)航頁(yè)面中需要導(dǎo)入路由import { Router } from '@angular/router';
// 頁(yè)面帶參數(shù)跳轉(zhuǎn)方法
goUser() {
this.router.navigate(['/user'], {
queryParams: {
name: '另一個(gè)涼雨'
}
});
}
- userComponent組件中接收參數(shù)
// 接收傳過(guò)來(lái)的參數(shù)
this.name = this.routeInfo.snapshot.queryParams['name'];
console.log(this.name)
3.3师郑、http接口請(qǐng)求
- 一個(gè)項(xiàng)目肯定是離不開(kāi)后端交互的环葵,那我們就需要用到http的接口請(qǐng)求來(lái)獲取數(shù)據(jù),考慮到http使用比較頻繁我們可以把請(qǐng)求封裝成一個(gè)服務(wù)宝冕。我們新建一個(gè)以service結(jié)尾的http.service.ts文件代表服務(wù)類文件张遭,引入需要的庫(kù),@Injectable(),angular的注入服務(wù)地梨,Http請(qǐng)求和Headers請(qǐng)求頭的設(shè)置菊卷,引入rxjs的Observable方法處理異步,關(guān)于rxjs的Observable詳細(xì)介紹可查看這篇文章宝剖,關(guān)于rxjs的Observable簡(jiǎn)單入門(mén)介紹可查看另一篇文章洁闰,寫(xiě)的都挺不錯(cuò)的。
import { Injectable } from '@angular/core';
import { Http, Headers } from '@angular/http';
import { Observable } from 'rxjs/Observable';
import 'rxjs/Rx';
- 以下是對(duì)get請(qǐng)求和post請(qǐng)求的封裝万细,注意需要在class類方式上面加上@Injectable()表示可通過(guò)服務(wù)注入
@Injectable()
export class ServiceBaseService {
param: any;
constructor(private http: Http) { }
/**
* @param {string} url地址
* @param {any} [options]可選提交的參數(shù)
* @param {any} [header]可選設(shè)置的頭信息
* @memberof ServiceBaseService
* @title: 封裝一個(gè)get請(qǐng)求的基礎(chǔ)類
*/
getData(url: string, options?: any, myheaders?: any): Observable<any> {
// 配置請(qǐng)求頭
const myHeaders: Headers = new Headers();
// tslint:disable-next-line:forin
for (const key in myheaders) {
myHeaders.append(key, myheaders[key]);
};
url += (url.indexOf('?') < 0 ? '?' : '&') + this.param(options);
return this.http.get(url, { headers: myHeaders }).map(res => res.json());
}
/**
* @param url地址
* @param options提交的數(shù)據(jù)
* @param myheaders可選參數(shù)設(shè)置頭
* @title:封裝一個(gè)post請(qǐng)求數(shù)據(jù)的
*/
postData(url: string, options: any, myheaders?: any): Observable<any> {
const myHeaders: Headers = new Headers();
myHeaders.append('Content-Type', 'application/json');
// tslint:disable-next-line:forin
for (const key in myheaders) {
myHeaders.append(key, myheaders[key]);
}
return this.http.post(url, options, { headers: myHeaders });
}
}
- 我們?cè)趗ser.component.ts中引入上面所封裝的接口請(qǐng)求服務(wù)扑眉,需要import進(jìn)來(lái),還需要在@Component中進(jìn)行注入和constructor構(gòu)造函數(shù)中聲名
import { ServiceBaseService } from './http.service';
@Component({
providers: [ ServiceBaseService ],
})
constructor( private ServiceBaseService: ServiceBaseService ) {}
- 接口測(cè)試的方式調(diào)用如下
testGetData() {
this.url = 'xxxx'; //此處為調(diào)用接口的地址
this.param = {'Appid': 'workflow', 'Appsecret': 'xxx'}; //接口調(diào)用傳參
this.ServiceBaseService.postData(this.url, this.param).subscribe({
next: function(value) { //成功后返回?cái)?shù)據(jù)
console.log(value);
},
error: function(error) { //報(bào)錯(cuò)拋出異常
console.log('Throw Error: ' + error);
}
});
}
-
測(cè)試接口調(diào)用成功
測(cè)試結(jié)果圖
四、組件
組件生命周期
- ngOnChanges:在ngOnInit之前赖钞, 當(dāng)數(shù)據(jù)綁定輸入屬性的值發(fā)生變化時(shí)調(diào)用腰素。 并且有一個(gè)SimpleChanges類型的參數(shù),它其實(shí)是一個(gè)類型為SimpleChange雪营,并且鍵值為屬性名的數(shù)組弓千。
- ngOnInit:在第一次ngOnChanges之后。
- ngDoCheck:每次Angular變化檢測(cè)時(shí)献起。
- ngAfterContentInit:在組件使用 ng-content 指令的情況下计呈,Angular 會(huì)在將外部?jī)?nèi)容放到視圖后用。它主要用于獲取通過(guò) @ContentChild 或 @ContentChildren 屬性裝飾器查詢的內(nèi)容視圖元素征唬。
- ngAfterContentChecked:在組件使用 ng-content 指令的情況下捌显,Angular 會(huì)在檢測(cè)到外部?jī)?nèi)容的綁定或者每次變化的時(shí)候調(diào)用。
- ngAfterViewInit:在組件相應(yīng)的視圖初始化之后調(diào)用总寒,它主要用于獲取通過(guò) @ViewChild 或 @ViewChildren 屬性裝飾器查詢的視圖元素扶歪。
- ngAfterViewChecked:在子組件視圖和子視圖檢查之后。
- ngOnDestroy:在Angular銷毀組件/指令之前。
代碼實(shí)現(xiàn):
import { Component, OnInit, OnChanges, DoCheck, AfterContentInit,
AfterContentChecked, AfterViewChecked, AfterViewInit, OnDestroy } from '@angular/core';
@Component({
selector: 'sl-user',
templateUrl: 'xxx.html', // 組件對(duì)應(yīng)的html頁(yè)面
styleUrls: ['xxx.css'] // 組件對(duì)應(yīng)的樣式文件
})
export class UserComponent implements OnInit, OnChanges,
AfterContentInit, DoCheck,
AfterContentChecked, AfterViewChecked,
AfterViewInit, OnDestroy {
constructor() {
ngOnInit() {
}
ngOnChanges() {
console.log('On changes');
}
// 臟值檢測(cè)器被調(diào)用后調(diào)用
ngDoCheck() {
console.log('Do check');
}
// 組件銷毀之前
ngOnDestroy() {
console.log('Destroy');
}
// 組件-內(nèi)容-初始化完成 PS:指的是ContentChild或者Contentchildren
ngAfterContentInit() {
console.log('After content init');
}
// 組件內(nèi)容臟檢查完成
ngAfterContentChecked() {
console.log('After content checked');
}
// 組件視圖初始化完成 PS:指的是ViewChild或者ViewChildren
ngAfterViewInit() {
console.log('After view init');
}
// 組件視圖臟檢查完成之后
ngAfterViewChecked() {
console.log('After view checked');
}
}
}
組件運(yùn)行到銷毀生命周期函數(shù)執(zhí)行打印結(jié)果善镰,如下圖:
五妹萨、其它
TypeScript
在學(xué)習(xí)探索angular4.0中,我發(fā)現(xiàn)TypeScript技術(shù)還是需要跟進(jìn)下學(xué)習(xí)的炫欺,不然遇到一些問(wèn)題都不知道怎么處理乎完,現(xiàn)在TypeScript也是前端學(xué)習(xí)的一個(gè)熱門(mén)和趨勢(shì),推薦TypeScript官網(wǎng)學(xué)習(xí)地址