我們?cè)谑褂肁ngular框架構(gòu)建Web應(yīng)用時(shí),往往離不開(kāi)各種REST API的調(diào)用。這次,我將針對(duì)該話題和您展開(kāi)深入討論。當(dāng)然,由于會(huì)涉及到一定的代碼級(jí)討論,因此您可能需要對(duì)HTTP、HTML、TypeScript、以及Angular框架有所了解。下面,先讓我們來(lái)簡(jiǎn)單瀏覽一下Angular框架中的服務(wù)和依賴注入的相關(guān)知識(shí)。
什么是Angular服務(wù)?
在真實(shí)的應(yīng)用場(chǎng)景中,多個(gè)組件需要從外部源訪問(wèn)數(shù)據(jù)。而由Typescript類編寫的Angular服務(wù),往往可以為此充當(dāng)單一的、可重用的數(shù)據(jù)訪問(wèn)點(diǎn)。我們通過(guò)在可注入服務(wù)類(injectable service class)中定義好此類處理任務(wù),就能夠讓任何組件輕松地訪問(wèn)到這些已定義的任務(wù)。
什么是依賴注入?
作為一種設(shè)計(jì)模式,Angular的依賴注入 (Dependency Injection,DI) 可被用于為各個(gè)組件提供所需的各項(xiàng)依賴性服務(wù)。例如,當(dāng)組件需要將某項(xiàng)任務(wù)委托給某個(gè)服務(wù)時(shí),我們就可以將該服務(wù)注入到組件中,讓組件能夠順利地訪問(wèn)到該服務(wù)類。為此,我們需要在服務(wù)類中使用@Injectable()裝飾器(decorator),并允許Angular將其作為依賴項(xiàng),注入到組件中的元數(shù)據(jù)(metadata)上。
Angular中的REST API調(diào)用
假設(shè)我們需要一個(gè)REST API來(lái)管理諸如:創(chuàng)建、更新和刪除博客等操作。那么,讓我們來(lái)看看該如何用它在MongoDB數(shù)據(jù)庫(kù)中插入博客的內(nèi)容。
調(diào)用REST API的第一步是在Angular CLI中輸入如下命令:
ng generate service RESTAPIService
它會(huì)在現(xiàn)有項(xiàng)目的/src/app文件夾中,創(chuàng)建一個(gè)TypeScript類--RESTAPIService。接著,您可以將如下TypeScript代碼添加到對(duì)應(yīng)的樣板文件(boilerplate)中。
TypeScript
import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http'
@Injectable({
providedIn: 'root'
})
export class RESTAPIService {
constructor(private http: HttpClient) { }
httpOptions = {
headers: new HttpHeaders({
'Content-Type': 'application/json'
})
};
postBlog(blog: any) {
let url = "http://localhost:3000/blogs";
return this.http.post(url, blog, this.httpOptions);
}
}
如上代碼段所示,@Injectable()裝飾器會(huì)使得Angular項(xiàng)目中的RESTAPIService滿足DI要求。而元數(shù)據(jù)providedIn: 'root'指定了RestAPIService在所有組件中都是可見(jiàn)的。提供者對(duì)象(provider object)可以在該服務(wù)本身的元數(shù)據(jù)中被指定,或者是在任何特定的模塊及組件中被注冊(cè)。若要在任何特定的模塊或組件中注冊(cè)它,我們則需要分別使用@NgModule()或@Component()裝飾器。
該服務(wù)通過(guò)注入一個(gè)內(nèi)置依賴項(xiàng)HttpClient,來(lái)與服務(wù)器進(jìn)行通信。HttpClient服務(wù)會(huì)利用observable,向服務(wù)器發(fā)起HTTP請(qǐng)求。在使用HttpClient之前,我們需要在根模塊AppModule中導(dǎo)入Angular的HttpClientModule。
HttpHeader類可以表示HTTP請(qǐng)求的各個(gè)標(biāo)頭配置選項(xiàng)。針對(duì)該博客的插入操作,我們需要添加帶有application/json值的Content-Type。它會(huì)將博客內(nèi)容指定為JSON格式。在postBlog()方法中,作為參數(shù)被接收的博客內(nèi)容,將使用HTTP的POST方法,被發(fā)送到REST API的URI--http://localhost:3000/blogs處。服務(wù)器端會(huì)處理請(qǐng)求,并在MongoDB數(shù)據(jù)庫(kù)中插入各種JSON文檔。下圖展示了用于收集博客內(nèi)容的Angular表單,可能包含的博客標(biāo)題、片段和正文字段。
在Angular中,雙向數(shù)據(jù)綁定可被用于從Angular表單處收集用戶的輸入。屬性指令[(ngModel)]實(shí)現(xiàn)了雙向綁定,以便在模板驅(qū)動(dòng)的??Angular表單??中,讀取和寫入用戶的輸入值。有關(guān)此類雙向數(shù)據(jù)綁定的具體內(nèi)容,請(qǐng)參見(jiàn)??AngularDocs??。
事件綁定主要被用于綁定各個(gè)事件處理器,以便處理由用戶操作引發(fā)的事件。針對(duì)本例中的博客插入操作,每當(dāng)用戶單擊提交按鈕時(shí),就會(huì)觸發(fā)并執(zhí)行saveBlog()方法。
HTML
<form name="blogForm" action="" method="POST">
<table>
<tr>
<td colspan="2"><h1>Post New Blog</h1></td>
<td></td></tr>
<tr>
<td><label>Enter Title</label></td>
<td><input type="text" name="title" [(ngModel)]="title" placeholder="Enter Blog Title here ...."></td>
</tr>
<tr>
<td><label>Blog Snippet</label></td>
<td><input type="text" name="snippet" [(ngModel)]="snippet" placeholder="Enter Blog Snippet here ...."></td>
</tr>
<tr>
<td><label>Blog Body</label></td>
<td><textarea name="body" [(ngModel)]="body" placeholder="Enter Blog Body here ...."></textarea></td>
</tr>
<tr>
<td align="center" colspan="4">
<button type="submit" value="Submit" (click)="saveBlog()">Submit</button>
</td>
</tr>
</table>
</form>
如上述代碼段所示,TypeScript類會(huì)使用DI技術(shù),在組件中注入RESTAPIService。它從本地項(xiàng)目目錄中導(dǎo)入服務(wù),并將其實(shí)例化為構(gòu)造函數(shù)參數(shù)。
saveBlog()方法則會(huì)從TypeScript變量(包括:標(biāo)題、片段和正文)中讀取用戶的輸入數(shù)據(jù),并構(gòu)造出一個(gè)JSON對(duì)象--blog。它使用服務(wù)中定義的postBlog方法,并訂閱由Httpclient服務(wù)返回的可觀察對(duì)象,來(lái)跟蹤HTTP請(qǐng)求的狀態(tài)。如果它成功地完成了相關(guān)操作,用戶就會(huì)被導(dǎo)航到ViewBlogs路由處,并被呈現(xiàn)博客內(nèi)容的列表。而如果出現(xiàn)了某個(gè)錯(cuò)誤,它會(huì)在控制臺(tái)上顯示一條錯(cuò)誤消息。
TypeScript
import { Component, OnInit } from '@angular/core';
import { RESTAPIService } from '../restapidata.service';
import { Router } from "@angular/router"
@Component({
selector: 'app-postblog',
templateUrl: './postblog.component.html',
styleUrls: ['./postblog.component.css']
})
export class PostblogComponent implements OnInit {
title = '' snippet = '' body = ''
constructor(private service: RESTAPIService, private router: Router) { }
ngOnInit(): void {
}
saveBlog() {
let blog = { title: this.title, snippet: this.snippet, body: this.body };
this.service.postBlog(blog).subscribe({
error: (err) => { console.error(err) },
complete: () => { this.router.navigate(['viewblogs']) }
});
}
}
小結(jié)
上文向您概述了如何使用Angular框架進(jìn)行REST API調(diào)用的簡(jiǎn)單過(guò)程。如果您是對(duì)此類技術(shù)感興趣的Web開(kāi)發(fā)者,可以在理解基本原理的基礎(chǔ)上,通過(guò)上面介紹的代碼段,去使用Angular發(fā)起REST API調(diào)用。
原文標(biāo)題:??How to Make a REST API Call in Angular??,作者:Muhammad Imran