Angular HttpClient使用RxJS Observable例子

编程教程 > WEB > JavaScript (2107) 2024-11-26 14:39:04

习使用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


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




 


评论
User Image
提示:请评论与当前内容相关的回复,广告、推广或无关内容将被删除。

相关文章
Angular HttpClient使用RxJS Observable例子,习使用Angular2  HttpClient服务从在线REST API获取数据并将其作为Observable对象/数...
httpclient4.5使用详解 httpclient 4.5 post传递json参数
Spring Boot 2.0 @JsonFormat(pattern = "yyyy-MM-dd",timezone = "GMT+8") 注解格式化日期失效原因及解决。
Log4j 2 简介       Apache Log4j 2是对Log4j 1.x的升级,相对于其先前版本进行了重大改进,例如性能改进,自动重新加载已修改的配置文件,java 8 lambda...
步骤:1、配置文件webpack.config.js:  {     test:/\.css$/,     loader:'style-loader!css-loader'  ...
一、项目环境Spring Boot 2.1.2.RELEASEshiro-spring 1.4二、去掉URL jsessionid在shiro配置中,配置关闭url中显示sessionId ...
引言AES代表高级加密系统,它是一种对称加密算法
使用方法toFixed.使用案例letwidth=5.556;console.log(width.toFixed(2))输出内容:5.56使用提示,toFixed必须是数字类型,如果是字符串需要...
环境说明1.MySQL5.7(注意,json格式最低需要改版本支持);2.存json数据的数据库字段类型必须是json,不能是varchar;
在vue2.0中使用了axios库,设置请求头Content-Type='application/json;charset=UTF-8'无效axios.defaults.headers.comm...
1.打开github nodejs源码地址GitHub - nodesource/distributions: NodeSource Node.js Binary Distributions2....
现有js数组数据如下:let dataArray=[{id:1,name:'张三'},{id:2,name:'李四'}];根据id获取js数组的对象let findId=1; let findO...
该插件是基于bootstrap框架开发的一个table插件,功能强大实用性强展示结果截图:1.下载bootstrap table插件,下载2.导入插件相关的cs
​JavaScript 数学小数精确计算&lt;!DOCTYPE html&gtl; &lt;html&gtl; &lt;head&gtl; &lt;title&gtl;&lt;/tit...
JavaScript/JS数组清空,删除数组内所有数据。Array=[]与Array.length=0的区别