在这篇文章中,你将学习如何在Angular应用程序中创建一个简单的模拟api来返回json数据,而无需创建后台API。
有些时候,如果没有后台代码,我们想使用API代码来测试数据组件。
本教程解释了如何在Angular应用程序中为返回json对象的模拟数据创建一个后端REST API。
首先,使用ng -version检查angular cli是否安装。
C:\Users\Kiran>ng --version
_ _ ____ _ ___
/ \ _ __ __ _ _ _| | __ _ _ __ / ___| | |_ _|
/ △ \ | '_ \ / _` | | | | |/ _` | '__| | | | | | |
/ ___ \| | | | (_| | |_| | | (_| | | | |___| |___ | |
/_/ \_\_| |_|\__, |\__,_|_|\__,_|_| \____|_____|___|
|___/
Angular CLI: 12.0.1
Node: 14.17.0
Package Manager: npm 7.11.1
OS: win32 x64
Angular: undefined
...
Package Version
------------------------------------------------------
@angular-devkit/architect 0.1200.1 (cli-only)
@angular-devkit/core 12.0.1 (cli-only)
@angular-devkit/schematics 12.0.1 (cli-only)
@schematics/angular 12.0.1 (cli-only)
typescript 3.6.3
如果已经安装了Angular cli,使用npm install @angular/cli 命令来安装它。
接下来,使用ng new命令创建一个Angular应用程序
B:\githubwork\angular-mock-api-json>ng new
? What name would you like to use for the new workspace and initial project? no
? Would you like to add Angular routing? Yes
? Which stylesheet format would you like to use? CSS
CREATE no/angular.json (3015 bytes)
CREATE no/package.json (1064 bytes)
CREATE no/README.md (1048 bytes)
CREATE no/tsconfig.json (783 bytes)
CREATE no/.editorconfig (274 bytes)
CREATE no/.gitignore (604 bytes)
CREATE no/.browserslistrc (703 bytes)
CREATE no/karma.conf.js (1419 bytes)
CREATE no/tsconfig.app.json (287 bytes)
CREATE no/tsconfig.spec.json (333 bytes)
CREATE no/src/favicon.ico (948 bytes)
CREATE no/src/index.html (288 bytes)
CREATE no/src/main.ts (372 bytes)
CREATE no/src/polyfills.ts (2820 bytes)
CREATE no/src/styles.css (80 bytes)
CREATE no/src/test.ts (743 bytes)
CREATE no/src/assets/.gitkeep (0 bytes)
CREATE no/src/environments/environment.prod.ts (51 bytes)
CREATE no/src/environments/environment.ts (658 bytes)
CREATE no/src/app/app-routing.module.ts (245 bytes)
CREATE no/src/app/app.module.ts (393 bytes)
CREATE no/src/app/app.component.html (23809 bytes)
CREATE no/src/app/app.component.spec.ts (1045 bytes)
CREATE no/src/app/app.component.ts (206 bytes)
CREATE no/src/app/app.component.css (0 bytes)
√ Packages installed successfully.
Directory is already under version control. Skipping initialization of git.
使用JSON的Backendless REST API的json-server
json-server 是一个基于Express的网络服务器,它拥有所有使用JSON作为数据库的REST API操作。
它帮助UI开发者使用JSON文件作为后端数据库来制作REST API的原型或模拟。
它允许在5分钟内设置和运行REST API服务器,无需编码,并帮助开发人员测试UI组件。
JSON-服务器的特点
- 对象的任何变化都会更新数据库JSON文件
- 它还提供项目列表中的分页数据
- 提供认证以增加安全性
- 使用路由选项自定义路由
--routes - 添加中间件代码以应用业务逻辑
--middlewares - 它更容易在5分钟内集成
- 支持404和重复等验证方式
npm install --save json-server
接下来在项目目录下创建一个文件夹api 。
创建一个数据库.json在api
{
users:[]
}
我们可以插入假数据或使用faker npm库。
faker npm库可以生成假数据
faker.js是一个用于生成虚假实时数据的npm库,首先将faker安装到angular应用程序中。
npm install faker --save
接下来,使用javascript代码插入假数据
- 创建一个用户数据库,保存用户信息的列表
- 使用for循环插入100个带有假数据的用户并推送到用户数组中。
- 我们在数据库字符串中拥有用户数组对象。
- 使用JSON.stringfy funciton将这个对象转换成json字符串。
- 我们必须使用fs模块的
writeFile方法创建一个数据库.json。 writeFile接受文件路径、json对象、编码和回调。- 如果没有创建json文件,回调会抛出一个错误。
这里是InsertIntoDB.js,它创建了数据库.json文件。
var faker = require('faker');
var fs = require('fs');
var database = { users: [] };
for (var i = 1; i <= 100; i++) {
database.users.push({
id: i,
name: faker.name.findName(),
email: faker.internet.email(),
username: faker.commerce.userName,
password: faker.commerce.password,
});
}
var json = JSON.stringify(database);
fs.writeFile('api/database.json', json, 'utf8', (err) => {
if (err) { console.error(err); return; };
console.log("database.json created");
});
让我们在package.json中为以下内容配置npm脚本
- insert:它在json字符串中生成伪造的数据并创建数据库.json。
"insert": "node ./api/InsertIntoDB.js",
- server:让我们配置json-server来启动服务器和输入数据库文件。
"server": "json-server --watch ./api/database.json"
这里是package.json文件
{
"name": "angular-mock-api-json",
"version": "0.0.0",
"scripts": {
"ng": "ng",
"start": "ng serve",
"build": "ng build",
"watch": "ng build --watch --configuration development",
"test": "ng test",
"insert": "node ./api/InsertIntoDB.js",
"server": "json-server --watch ./api/database.json"
},
"private": true,
"dependencies": {
"@angular/animations": "~12.0.1",
"@angular/common": "~12.0.1",
"@angular/compiler": "~12.0.1",
"@angular/core": "~12.0.1",
"@angular/forms": "~12.0.1",
"@angular/platform-browser": "~12.0.1",
"@angular/platform-browser-dynamic": "~12.0.1",
"@angular/router": "~12.0.1",
"faker": "^5.5.3",
"json-server": "^0.16.3",
"rxjs": "~6.6.0",
"tslib": "^2.1.0",
"zone.js": "~0.11.4"
},
"devDependencies": {
"@angular-devkit/build-angular": "~12.0.1",
"@angular/cli": "~12.0.1",
"@angular/compiler-cli": "~12.0.1",
"@types/jasmine": "~3.6.0",
"@types/node": "^12.11.1",
"jasmine-core": "~3.7.0",
"karma": "~6.3.0",
"karma-chrome-launcher": "~3.1.0",
"karma-coverage": "~2.0.3",
"karma-jasmine": "~4.0.0",
"karma-jasmine-html-reporter": "^1.5.0",
"typescript": "~4.2.3"
},
"_id": "no@0.0.0"
}
接下来使用npm run命令运行上述代码来创建一个数据库
npm run insert
这将在api文件夹中创建一个数据库.json文件。
使用npm run命令启动json服务器
B:\githubwork\angular-mock-api-json>npm run server
> no@0.0.0 server
> json-server --watch ./api/database.json
\{^_^}/ hi!
Loading ./api/database.json
Done
Resources
http://localhost:3000/users
Home
http://localhost:3000
Type s + enter at any time to create a snapshot of the database
Watching...
这将启动服务器并可在http://localhost:3000/users。
默认情况下,这提供了不同的api的可访问性
| URL | HTTP方法类型 | 描述 |
|---|---|---|
| /users | 获取 | 用户列表 |
| /users/{id} | GET | 通过ID检索用户 |
| /users | 传送 | 创建一个用户对象 |
| /users/{id} | PUT | 通过ID更新一个用户对象 |
| /users/{id} | PATCH | 根据Id更新一个有部分属性的用户对象 |
| /users{id} | DELETE |
如果使用POST,PUT,PATCH,DELETE请求对用户对象做任何更改,JSOn-server会立即更新数据库.json。
消耗Mock数据的Angular实例
在Angular应用程序中消耗REST API有几个步骤。前端应用程序与后端应用程序或REST API使用HTTP连接进行通信@angular/common/http 提供HttpClient类。
HttpClient是用户连接并向REST API发出HTTP请求的组件。
在使用HttpClient之前,你必须先导入HttpClientModule
设置HttpClientModule到模块中
将HttpClientModule导入到angularapp.module.ts 。
这个模块中所有可用的类和服务都可以在app.module.ts的所有组件中访问。
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { HttpClientModule } from '@angular/common/http';
@NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule,
AppRoutingModule,
HttpClientModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
首先为用户数据创建一个接口模型。你可以选择[接口或类作为模型](/angular-model-class-interface)。
export interface User {
id: number;
name: string;
email: string;
username: string;
}
让我们先在Angular Component中创建一个组件app.component.ts。
-
创建了一个用户数组对象
-
在构造函数中用空数组初始化用户数组,如果你跳过这一步,你会得到一个错误。
Property 'users' has no initializer and is not definitely assigned in the constructor.ts(2564)你可以查看更多关于如何解决这个错误的信息
-
在构造函数中注入
HttpClient,以使用HttpClient类方法 -
使用http
get请求HttpClient.get -
getAPI以JSON对象返回响应,并转换为Typescript User对象。 -
在html模板文件中,使用ngFor循环遍历
users对象并显示在用户界面上。 -
在scss文件中,添加css样式来替代表格行的颜色。app.component.ts:
import { HttpClient } from '@angular/common/http';
import { Component } from '@angular/core';
import { Observable } from 'rxjs';
import { User } from './model/User';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.scss']
})
export class AppComponent {
users: User[];
title = 'angular-crud-mock-api';
constructor(private http: HttpClient) {
this.users = [];
this.getUsers();
}
getUsers() {
console.log('calling')
this.http.get('http://localhost:3000/users')
.subscribe(res => this.users =
res as User[]);
}
}
app.component.html:
Users List
id
username
email
{{user.id}}
{{user.name}}
{{user.email}}
app.component.scss:
table {
border-collapse: collapse;
width: 100%;
th,
tr {
border: 1px solid #ccc;
}
th,
td {
text-align: left;
}
tr:nth-child(even) {
background-color: #f0f0f0;
}
}
这个例子调用模拟的REST API并显示在表格中。
输出
总结
总结一下,我们学习了一个一步一步的教程,用cli创建一个angular应用程序 添加json-server作为模拟API服务器 添加faker作为CRUD API的假数据 写一个package.json脚本将数据插入数据库json并启动json服务器 添加httpClientModule并在angular应用程序组件中使用Mock API。