文章图片
事件绑定主要被用于绑定各个事件处理器 , 以便处理由用户操作引发的事件 。 针对本例中的博客插入操作 , 每当用户单击提交按钮时 , 就会触发并执行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="https://www.sohu.com/a/Submit" (click)="saveBlog()">Submit</button>
</td>
</tr>
</table>
</form>
如上述代码段所示 , TypeScript类会使用DI技术 , 在组件中注入RESTAPIService 。 它从本地项目目录中导入服务 , 并将其实例化为构造函数参数 。
saveBlog()方法则会从TypeScript变量(包括:标题、片段和正文)中读取用户的输入数据 , 并构造出一个JSON对象--blog 。 它使用服务中定义的postBlog方法 , 并订阅由Httpclient服务返回的可观察对象 , 来跟踪HTTP请求的状态 。 如果它成功地完成了相关操作 , 用户就会被导航到ViewBlogs路由处 , 并被呈现博客内容的列表 。 而如果出现了某个错误 , 它会在控制台上显示一条错误消息 。
复制
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']) }
});
}
}
小结 上文向您概述了如何使用Angular框架进行REST API调用的简单过程 。 如果您是对此类技术感兴趣的Web开发者 , 可以在理解基本原理的基础上 , 通过上面介绍的代码段 , 去使用Angular发起REST API调用 。
原文标题:How to Make a REST API Call in Angular , 作者:Muhammad Imran
特别声明:本站内容均来自网友提供或互联网,仅供参考,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
