{% raw %}

带有 RxJS Observable的 Angular HttpClient示例

原文: https://howtodoinjava.com/angular/rxjs-observable-httpclient/

了解如何使用 Angular HttpClient服务从在线 REST API 获取数据,并将其作为Observable对象/数组返回。 在发生任何数据事件时,observable的订户将做出反应。

  1. Table of Contents
  2. HTTPClient Setup
  3. Create service which return Observable
  4. Create observer which subscribe to Observable
  5. View HTML Template
  6. Demo

HTTPClient设置

要使用HTTPClient服务,您需要执行两个步骤:

  1. 在根模块中导入HttpClientModule


@angular/common/http包中导入HttpClientModule模块,并将其条目添加到@NgModuleimports属性中。

  1. import { BrowserModule } from '@angular/platform-browser';
  2. import { HttpClientModule } from '@angular/common/http';
  3. import { NgModule } from '@angular/core';
  4. import { AppComponent } from './app.component';
  5. @NgModule({
  6. declarations: [
  7. AppComponent
  8. ],
  9. imports: [
  10. BrowserModule,
  11. HttpClientModule
  12. ],
  13. providers: [],
  14. bootstrap: [AppComponent]
  15. })
  16. export class AppModule { }
  1. 在服务构造器中注入HttpClient


现在,在开始使用它时,在服务代码中注入实际的HttpClient服务。

  1. import { Injectable } from '@angular/core';
  2. import { HttpClient } from '@angular/common/http';
  3. @Injectable({
  4. providedIn: 'root'
  5. })
  6. export class EmployeeService {
  7. constructor(private http: HttpClient) { }
  8. }

创建返回Observable的服务

我们将使用通过 REST 模拟服务器创建的 REST API。 让我们编辑员工服务类别的代码,并从中返回Observable

  1. import { Injectable } from '@angular/core';
  2. import { HttpClient } from '@angular/common/http';
  3. import { Employee } from '../model/employee';
  4. import { Observable } from 'rxjs';
  5. @Injectable({
  6. providedIn: 'root'
  7. })
  8. export class EmployeeService {
  9. constructor(private http: HttpClient) { }
  10. public getEmployees(): Observable<Employee[]>
  11. {
  12. const url = 'http://localhost:3000/employees';
  13. return this.http.get<Employee[]>(url);
  14. }
  15. }

上面的代码点击 REST API "/employees"并获取employee数组。 然后,它返回employee数组作为可观察的集合。 任何方法都可以订阅它来监听此数组上的数据事件。

仅供参考,Employee是用于存储数据的模型类。

  1. export class Employee {
  2. public id: number;
  3. public name: string;
  4. public status: string;
  5. constructor(id:number, name:string, status:string) {
  6. this.id = id;
  7. this.name = name;
  8. this.status = status;
  9. }
  10. }

创建订阅了Observable的观察者

我们将在组件文件中创建订户。 它将从可观察数组中读取数据并分配给模型属性。 模型属性可用于映射来自 UI 的数据。

  1. import { Component } from '@angular/core';
  2. import { EmployeeService } from './service/employee.service';
  3. import { Employee } from './model/employee';
  4. @Component({
  5. selector: 'app-root',
  6. templateUrl: './app.component.html',
  7. styleUrls: ['./app.component.css']
  8. })
  9. export class AppComponent {
  10. title = 'app';
  11. employees = new Array<Employee>();
  12. constructor( empService:EmployeeService ) {
  13. empService.getEmployees().subscribe(response =>
  14. {
  15. this.employees = response.map(item =>
  16. {
  17. return new Employee(
  18. item.id,
  19. item.name,
  20. item.status
  21. );
  22. });
  23. });
  24. }
  25. }

查看 HTML 模板

是时候更新视图 HTML 了,该 HTML 将尽快提供employee数组数据。

  1. <h1>
  2. Angular HTTP Service Example
  3. </h1>
  4. <table border="1" style="width: 33%">
  5. <tr>
  6. <th>Id</th>
  7. <th>Name</th>
  8. <th>Status</th>
  9. </tr>
  10. <tr *ngFor="let emp of employees">
  11. <td>{{ emp.id }}</td>
  12. <td>{{ emp.name }}</td>
  13. <td>{{ emp.status }}</td>
  14. </tr>
  15. </table>

演示

要测试以上编写的代码,您将启动模拟 REST 服务器以及 angular 应用。

  1. 使用此命令启动模拟服务器。
    1. $ json-server --watch 'E:\ngexamples\db.json'
  1. 使用命令启动 Angular 应用。
    1. $ ng serve

在浏览器中检查应用。

246.md - 图1

带有 RxJS Observable的 Angular HttpClient示例

将您的评论放在源代码中。

学习愉快!

源码下载

{% endraw %}