欢迎来到之路教程(on itroad-com)

创建订阅 Observable 的观察者

我们将在组件文件中创建订阅者。
它将从 observable 数组中读取数据并分配给模型属性。
模型属性可用于从 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 了,它会在“员工数组”数据可用时立即呈现。

<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>
Angular HttpClient 服务

本文将介绍如何使用 Angular HttpClient服务从在线 REST API 获取数据并将其作为 Observable对象/数组返回。

创建返回 Observable 的服务

我们将使用 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是存储数据的模型类。

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

}

演示

要测试上述编写的代码,我们将启动模拟 REST 服务器以及 Angular 应用程序。

  • 使用此命令启动 Mock 服务器。
$ json-server --watch 'E:\ngexamples\db.json'
  • 使用命令启动Angular应用程序。
$ ng serve

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

HTTP客户端设置

要使用 HTTPClient服务,你需要做两步:

  • 在根模块中
    导入 HttpClientModule 从 @angular/common/http包中导入 HttpClientModule模块,并将其添加到 @NgModuleimports属性中。
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
    现在在开始使用它时在服务代码中注入实际的 HttpClient服务。
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
@Injectable({
  providedIn: 'root'
})
export class EmployeeService {
  constructor(private http: HttpClient) { }
}
日期:2020-09-17 00:09:15 来源:oir作者:oir