首頁>技術>

藉助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裡匯入:

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的實現程式碼:

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>

其中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方法:

80
最新評論
  • BSA-TRITC(10mg/ml) TRITC-BSA 牛血清白蛋白改性標記羅丹明
  • Python介面(GUI)程式設計PyQt5工具欄和選單