{% raw %}
原文: https://howtodoinjava.com/angular/rxjs-observable-httpclient/
了解如何使用 Angular HttpClient服务从在线 REST API 获取数据,并将其作为Observable对象/数组返回。 在发生任何数据事件时,observable的订户将做出反应。
Table of Contents
HTTPClient Setup
Create service which return Observable
Create observer which subscribe to Observable
View HTML Template
Demo要使用HTTPClient服务,您需要执行两个步骤:
-
从
@angular/common/http包中导入HttpClientModule模块,并将其条目添加到@NgModule的imports属性中。import { BrowserModule } from '@angular/platform-browser'; import { HttpClientModule } from '@angular/common/http'; import { NgModule } from '@angular/core'; import { AppComponent } from './app.component'; @NgModule({ declarations: [ AppComponent ], imports: [ BrowserModule, HttpClientModule ], providers: [], bootstrap: [AppComponent] }) export class AppModule { }
-
现在,在开始使用它时,在服务代码中注入实际的
HttpClient服务。import { Injectable } from '@angular/core'; import { HttpClient } from '@angular/common/http'; @Injectable({ providedIn: 'root' }) export class EmployeeService { constructor(private http: HttpClient) { } }
我们将使用通过 REST 模拟服务器创建的 REST API。 让我们编辑员工服务类别的代码,并从中返回Observable。
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Employee } from '../model/employee';
import { Observable } from 'rxjs';
@Injectable({
providedIn: 'root'
})
export class EmployeeService {
constructor(private http: HttpClient) { }
public getEmployees(): Observable<Employee[]>
{
const url = 'http://localhost:3000/employees';
return this.http.get<Employee[]>(url);
}
}上面的代码点击 REST API "/employees"并获取employee数组。 然后,它返回employee数组作为可观察的集合。 任何方法都可以订阅它来监听此数组上的数据事件。
仅供参考,Employee是用于存储数据的模型类。
export class Employee {
public id: number;
public name: string;
public status: string;
constructor(id:number, name:string, status:string) {
this.id = id;
this.name = name;
this.status = status;
}
}我们将在组件文件中创建订户。 它将从可观察数组中读取数据并分配给模型属性。 模型属性可用于映射来自 UI 的数据。
import { Component } from '@angular/core';
import { EmployeeService } from './service/employee.service';
import { Employee } from './model/employee';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
title = 'app';
employees = new Array<Employee>();
constructor( empService:EmployeeService ) {
empService.getEmployees().subscribe(response =>
{
this.employees = response.map(item =>
{
return new Employee(
item.id,
item.name,
item.status
);
});
});
}
}是时候更新视图 HTML 了,该 HTML 将尽快提供employee数组数据。
<h1>
Angular HTTP Service Example
</h1>
<table border="1" style="width: 33%">
<tr>
<th>Id</th>
<th>Name</th>
<th>Status</th>
</tr>
<tr *ngFor="let emp of employees">
<td>{{ emp.id }}</td>
<td>{{ emp.name }}</td>
<td>{{ emp.status }}</td>
</tr>
</table>要测试以上编写的代码,您将启动模拟 REST 服务器以及 angular 应用。
-
使用此命令启动模拟服务器。
$ json-server --watch 'E:\ngexamples\db.json'
-
使用命令启动 Angular 应用。
$ ng serve
在浏览器中检查应用。
带有 RxJS Observable的 Angular HttpClient示例
将您的评论放在源代码中。
学习愉快!
{% endraw %}
