Angular HttpClient使用RxJS Observable例子

位置:首页>文章>详情   分类: 教程分享 > Java教程   阅读(1204)   2023-03-28 11:29:14
习使用Angular  HttpClient服务从在线REST API获取数据并将其作为Observable对象/数组返回。任何数据事件,订阅者observable都会做出反应。
 

HTTPClient设置

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

1.在根模块中导入HttpClientModule

HttpClientModule@angular/common/http包中导入模块并在imports属性中添加它的条目@NgModule

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 { }
 

2.在服务构造函数中注入HttpClient

现在HttpClient在服务代码中注入实际服务作为开始使用它。

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';

@Injectable({
  providedIn: 'root'
})
export class EmployeeService {

  constructor(private http: HttpClient) { }

}

创建返回Observable的服务

我们将使用REST模拟服务器创建的REST API 。让我们编辑员工服务类的代码并Observable从中返回。
employee.service.ts:
 

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是存储数据的模型类。
employee.ts

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;
  }
   
}

创建订阅Observable的观察者

我们将在组件文件中创建订阅者。它将从可观察数组中读取数据并分配给模型属性。模型属性可用于从UI映射数据。
app.component.ts:
 

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 array数据可用时立即呈现。
app.component.html

<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服务器以及角度应用程序。
使用此命令启动Mock服务器。

$ json-server --watch 'E:\ngexamples\db.json'
使用命令启动angular应用程序。
$ ng serve

在浏览器中检查应用程序。
在浏览器中检查应用程序。




 
标签: Angular2 HttpClient
地址:https://www.leftso.com/article/453.html

相关阅读

Angular HttpClient使用RxJS Observable例子,习使用Angular2  HttpClient服务从在线REST API获取数据并将其作为Observable对象/数...
1.概述本教程将重点介绍如何使用Apache HttpClient 4发送自定义Cookie
typescript带参数的异步回调,JavaScript是一个单线程应用程序,如果我们继续将该线程用于所有任务,用户将最终等待阻碍用户体验的其他任务。为了解决这个问题,我们进行了异步编程。
Apache HttpClient 4.x 使用详解
HttpClient 4 按照POST重定向请求,本快速教程将展示如何配置Apache HttpClient 4以自动遵循POST请求的重定向。
在本教程中 - 我们将使用HttpClient 4进行POST - 首先使用授权,然后使用流畅的HttpClient API。最后 - 我们将讨论如何使用HttpClient上传文件。
HttpClient Basic Authentication基本认证,本教程将说明如何在Apache HttpClient 4上配置基本身份验证。
httpclient4.5使用详解 httpclient 4.5 post传递json参数
HttpClient的RestTemplate - Java配置示例