一、序章
關于Angular版本,Angular官方已經統一命名Angular 1.x統稱為Angular JS;Angular 2.x及以上統稱Angular
- 后續練習的源碼地址都會上傳到github庫上,源碼下載地址
回顧前端框架學習歷程
最早開始是對Angular JS比較熟悉,2015年那時候部門選擇了比較熱門的Angular JS結合ionic1.x加上codova平臺進行混合式的webAPP開發,那時候用Angular JS開發過挺多項目的,到如今也還有一些基于Angular JS的老項目在迭代開發和維護,但是存在一個問題就是現在很多人不會愿意再去學習舊版本的Angular JS了,因為谷歌升級發布的Angular可以說是一個大的跨度,他們并不是版本迭代升級這么簡單,你甚至可以完全把他們當做2個不同的框架進行學習,這也導致了之前的一部分Angular JS流量轉向了另外2大框架vue和react,同樣我們部門后續的主流技術棧也是轉向了vue和react。為什么要花時間去學習Angular?
Angular還是有很多的公司在使用,這也是我打算花點時間從新入門Angular4.x版本的原因,同時Angular一直都是一個很熱門的前端框架,并不是說它已經過時了(當然Angular JS是真的過時了),作為前端目前最流行的三大框架之一,還是值得花費一些時間去學習參考一下的。為什么選擇Angular4.x版本作為入門學習?
在選擇Angular版本的時候我思考了挺多,最后決定從Angular4.x快速入門寫起。為什么會選擇Angular4.x版本進行入門的學習呢?原因在于,之前一直在做vue和react的項目對Angular的學習還停留在以前的Angular JS,只是對后續Angular發布的版本保持著一定的關注,了解一些Angular相關的,知道Angular的版本迭代更新比較頻繁,到目前最新的正式版本已經迭代到7.x了,8.0的beta版本也已經發布,那給我的版本入門選擇也就比較多了。一開始我的打算是既然要學就學習最新的版本從7.x開始,后續我經過一些綜合的考慮放棄了7.x版本選擇了4.x版本作為入門,Angular4.x作為入門是比較合適的,Angular從1.x之后的版本迭代都是向下兼容,那4.x作為一個承上啟下的版本選擇它無疑是最合適的,可提供參考的社區資料也會更完善一些。后續我比較期待Angular8.0.0版本的發布,只因為它將正式包含Ivy Renderer ,對于Angular Ivy的了解可以參考這2篇博客進行理解 Ivy-Angular下一代渲染引擎 和 如何評價 Angular 的新Ivy Render。-
快速入門從哪些方面開始?
個人總結出來的一些經驗,怎樣以高效的方式入門學習一門新的前端框架,后續的快速入門我準備從以下幾個模塊開始:- 環境搭建
- 路由跳轉
- 頁面傳參及接口請求
- 組件
- 其它
一、環境搭建
基礎要求
開發環境配置方式
1. 通過git clone模板
- 通過git克隆官方快速入門模板,打開終端執行命令git clone https://github.com/angular/quickstart
- 用IDE打開克隆下來的工程,我用的是webstorm,然后安裝依賴,在當前工程目錄下執行npm install
- 依賴下載安裝完成后直接npm start運行
2.通過Angular CLI腳手架安裝
二、路由跳轉
- app.modules.ts中需要導入路由模塊
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(父子路由配置)
// 訪問/tabs跳轉到TabsPage,TabsPage只是一個底部導航。也相當于web網站的頂部導航或左側導航
// 所以需要訪問/tabs/demo,才會顯示導航和內容
// 訪問/tabs/tab1/test,顯示導航和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
為了讓我們鏈接到已設置的路由,我們需要使用 routerLink 指令,具體示例如下:
<nav>
<a routerLink="/">Home</a>
<a routerLink="/settings/password">Change password</a>
<a routerLink="/settings/profile">Profile Settings</a>
</nav>
當我們點擊以上的任意鏈接時,頁面不會被重新加載。反之,我們的路徑將在 URL 地址欄中顯示,隨后進行后續視圖更新,以匹配 routerLink 中設置的值。
- app.component.ts主頁中配置路由導航頁面
import { Component } from '@angular/core';
@Component({
selector: 'my-app',
template: `<div class="app">
<h1>歡迎來到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>我來自<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);
}
}
}
三、頁面跳轉傳參&接口請求
3.1、通過routerLink傳參方式
- 通過動態路由進行參數傳遞,app.module.ts在path路徑后面通過":"拼接需要傳遞的參數
export const ROUTES: Routes = [
{ path: '', pathMatch: 'full', redirectTo: '/' },
{ path: 'user/:name', component: UserComponent },
];
- app.component.ts中的跳轉鏈接
<a [routerLink]="['/user', '涼雨啊']">我的</a>
<!--或者方式2-->
<!--<a [routerLink]="['/user']" [queryParams]="{name:'涼雨啊'}">我的</a>-->
- userComponent.ts中接收,需要導入import { ActivatedRoute } from '@angular/router';
// 獲取參數值
this.name = this.routeInfo.snapshot.params['name'];
// 接收方式2傳遞的值
// this.name = this.routeInfo.snapshot.queryParams['name'];
console.log(this.name)
3.2、通過Router API中的navigate() 方法跳轉路由傳參
- app.module.ts配置路由
{ path: 'user', component: UserComponent },
- 在需要跳轉的導航頁面中需要導入路由import { Router } from '@angular/router';
// 頁面帶參數跳轉方法
goUser() {
this.router.navigate(['/user'], {
queryParams: {
name: '另一個涼雨'
}
});
}
- userComponent組件中接收參數
// 接收傳過來的參數
this.name = this.routeInfo.snapshot.queryParams['name'];
console.log(this.name)
3.3、http接口請求
- 一個項目肯定是離不開后端交互的,那我們就需要用到http的接口請求來獲取數據,考慮到http使用比較頻繁我們可以把請求封裝成一個服務。我們新建一個以service結尾的http.service.ts文件代表服務類文件,引入需要的庫,@Injectable(),angular的注入服務,Http請求和Headers請求頭的設置,引入rxjs的Observable方法處理異步,關于rxjs的Observable詳細介紹可查看這篇文章,關于rxjs的Observable簡單入門介紹可查看另一篇文章,寫的都挺不錯的。
import { Injectable } from '@angular/core';
import { Http, Headers } from '@angular/http';
import { Observable } from 'rxjs/Observable';
import 'rxjs/Rx';
- 以下是對get請求和post請求的封裝,注意需要在class類方式上面加上@Injectable()表示可通過服務注入
@Injectable()
export class ServiceBaseService {
param: any;
constructor(private http: Http) { }
/**
* @param {string} url地址
* @param {any} [options]可選提交的參數
* @param {any} [header]可選設置的頭信息
* @memberof ServiceBaseService
* @title: 封裝一個get請求的基礎類
*/
getData(url: string, options?: any, myheaders?: any): Observable<any> {
// 配置請求頭
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提交的數據
* @param myheaders可選參數設置頭
* @title:封裝一個post請求數據的
*/
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 });
}
}
- 我們在user.component.ts中引入上面所封裝的接口請求服務,需要import進來,還需要在@Component中進行注入和constructor構造函數中聲名
import { ServiceBaseService } from './http.service';
@Component({
providers: [ ServiceBaseService ],
})
constructor( private ServiceBaseService: ServiceBaseService ) {}
- 接口測試的方式調用如下
testGetData() {
this.url = 'xxxx'; //此處為調用接口的地址
this.param = {'Appid': 'workflow', 'Appsecret': 'xxx'}; //接口調用傳參
this.ServiceBaseService.postData(this.url, this.param).subscribe({
next: function(value) { //成功后返回數據
console.log(value);
},
error: function(error) { //報錯拋出異常
console.log('Throw Error: ' + error);
}
});
}
-
測試接口調用成功
測試結果圖
四、組件
組件生命周期
- ngOnChanges:在ngOnInit之前, 當數據綁定輸入屬性的值發生變化時調用。 并且有一個SimpleChanges類型的參數,它其實是一個類型為SimpleChange,并且鍵值為屬性名的數組。
- ngOnInit:在第一次ngOnChanges之后。
- ngDoCheck:每次Angular變化檢測時。
- ngAfterContentInit:在組件使用 ng-content 指令的情況下,Angular 會在將外部內容放到視圖后用。它主要用于獲取通過 @ContentChild 或 @ContentChildren 屬性裝飾器查詢的內容視圖元素。
- ngAfterContentChecked:在組件使用 ng-content 指令的情況下,Angular 會在檢測到外部內容的綁定或者每次變化的時候調用。
- ngAfterViewInit:在組件相應的視圖初始化之后調用,它主要用于獲取通過 @ViewChild 或 @ViewChildren 屬性裝飾器查詢的視圖元素。
- ngAfterViewChecked:在子組件視圖和子視圖檢查之后。
- ngOnDestroy:在Angular銷毀組件/指令之前。
代碼實現:
import { Component, OnInit, OnChanges, DoCheck, AfterContentInit,
AfterContentChecked, AfterViewChecked, AfterViewInit, OnDestroy } from '@angular/core';
@Component({
selector: 'sl-user',
templateUrl: 'xxx.html', // 組件對應的html頁面
styleUrls: ['xxx.css'] // 組件對應的樣式文件
})
export class UserComponent implements OnInit, OnChanges,
AfterContentInit, DoCheck,
AfterContentChecked, AfterViewChecked,
AfterViewInit, OnDestroy {
constructor() {
ngOnInit() {
}
ngOnChanges() {
console.log('On changes');
}
// 臟值檢測器被調用后調用
ngDoCheck() {
console.log('Do check');
}
// 組件銷毀之前
ngOnDestroy() {
console.log('Destroy');
}
// 組件-內容-初始化完成 PS:指的是ContentChild或者Contentchildren
ngAfterContentInit() {
console.log('After content init');
}
// 組件內容臟檢查完成
ngAfterContentChecked() {
console.log('After content checked');
}
// 組件視圖初始化完成 PS:指的是ViewChild或者ViewChildren
ngAfterViewInit() {
console.log('After view init');
}
// 組件視圖臟檢查完成之后
ngAfterViewChecked() {
console.log('After view checked');
}
}
}
組件運行到銷毀生命周期函數執行打印結果,如下圖:
五、其它
TypeScript
在學習探索angular4.0中,我發現TypeScript技術還是需要跟進下學習的,不然遇到一些問題都不知道怎么處理,現在TypeScript也是前端學習的一個熱門和趨勢,推薦TypeScript官網學習地址