习使用Angular HttpClient
服务从在线REST API获取数据并将其作为Observable
对象/数组返回。任何数据事件,订阅者observable
都会做出反应。
要使用HTTPClient
服务,您需要执行两个步骤:
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 { }
现在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
从中返回。
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;
}
}
我们将在组件文件中创建订阅者。它将从可观察数组中读取数据并分配给模型属性。模型属性可用于从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了,它会在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
在浏览器中检查应用程序。
http://blog.xqlee.com/article/453.html