在 Angular 中,雙向數據綁定用于從 Angular 表單收集用戶輸入。屬性指令 [(ngModel)] 實現了在模板驅動的 Angular 表單中讀取和寫入用戶輸入值的雙向綁定。

事件綁定用于綁定事件處理程序來處理用戶操作引發的事件。對于博客插入操作,當用戶單擊提交按鈕時,將執行 saveBlog() 方法。
<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 類使用 DI 技術在組件中注入 RESTAPIService。它從本地項目目錄中導入服務并將其實例化為構造函數參數。
saveBlog() 方法讀取 TypeScript 變量(title、snippet、body)中的用戶輸入數據,并構造一個 JSON 對象 blog。它使用服務中定義的 postBlog 方法,并訂閱 HttpClient 服務返回的可觀察對象,以跟蹤 HTTP 請求的狀態。如果操作成功完成,用戶將導航到 ViewBlogs 路由以顯示博客列表。如果出現錯誤,將在控制臺上顯示錯誤消息。
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']); }
});
}
}
本文概述了如何在 Angular 框架中進行 REST API 調用。具備相關技術基礎的 Web 開發人員可以借助本文內容,進一步增強對使用 Angular 發起 REST API 調用的理解和應用能力。
原文鏈接:How to Make a REST API Call in Angular