前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Angular In-memory Web API使用介绍

Angular In-memory Web API使用介绍

作者头像
Jerry Wang
发布2020-08-19 15:48:57
1.5K0
发布2020-08-19 15:48:57
举报

借助In-Memory Web API,Angular应用的HttpClient发送请求之后,会自动被In-memory Web API拦截,在in-memory数据存储器中管理,并返回模拟的数据响应。

After installing the module, the app will make requests to and receive responses from the HttpClient without knowing that the In-memory Web API is intercepting those requests, applying them to an in-memory data store, and returning simulated responses.

安装方法:使用下面的命令行:

npm install angular-in-memory-web-api --save

9秒钟就完成了安装:

在app module里导入:

代码语言:javascript
复制
import { HttpClientInMemoryWebApiModule } from 'angular-in-memory-web-api';
import { InMemoryDataService } from './in-memory-data.service';

并添加到NgModule的imports区域内:

目前还缺少一个in-memory-data.service,

使用下列的命令行生成:

ng generate service InMemoryData

inMemoryData service的实现代码:

代码语言:javascript
复制
import { Injectable } from '@angular/core';
import { InMemoryDbService } from 'angular-in-memory-web-api';
import { Hero } from './heroes/hero';

@Injectable({
  providedIn: 'root',
})
export class InMemoryDataService implements InMemoryDbService {
  createDb() {
    const heroes = [
      { id: 11, name: 'Dr Nice' },
      { id: 12, name: 'Narco' },
      { id: 13, name: 'Bombasto' },
      { id: 14, name: 'Celeritas' },
      { id: 15, name: 'Magneta' },
      { id: 16, name: 'RubberMan' },
      { id: 17, name: 'Dynama' },
      { id: 18, name: 'Dr IQ' },
      { id: 19, name: 'Magma' },
      { id: 20, name: 'Tornado' }
    ];
    return {heroes};
  }

  // Overrides the genId method to ensure that a hero always has an id.
  // If the heroes array is empty,
  // the method below returns the initial number (11).
  // if the heroes array is not empty, the method below returns the highest
  // hero id + 1.
  genId(heroes: Hero[]): number {
    return heroes.length > 0 ? Math.max(...heroes.map(hero => hero.id)) + 1 : 11;
  }
}

在hero service里,通过构造函数参数注入http client:

定义一个私有属性:

private heroesUrl = ‘api/heroes’; // URL to web api

这个property的值符合格式:/

其中base是请求的资源,而collectionName是in-memory-data-service.ts中的heroes对象:

在hero service里,将之前of返回的fake hero数据替换成使用http请求:

运行时的调试

入口是observable的subscribe方法:

http请求在http.js的intercept方法里被拦截了:

In-Memory Web API的服务方式是lazy load,即第一次需要服务之前才会初始化内存数据库:

此处调用开发人员在应用程序里编写的createDb方法:

本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2020-08-18 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 运行时的调试
相关产品与服务
数据保险箱
数据保险箱(Cloud Data Coffer Service,CDCS)为您提供更高安全系数的企业核心数据存储服务。您可以通过自定义过期天数的方法删除数据,避免误删带来的损害,还可以将数据跨地域存储,防止一些不可抗因素导致的数据丢失。数据保险箱支持通过控制台、API 等多样化方式快速简单接入,实现海量数据的存储管理。您可以使用数据保险箱对文件数据进行上传、下载,最终实现数据的安全存储和提取。
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档