Angular In-memory Web API使用介绍
借助In-Memory Web API,Angular應(yīng)用的HttpClient發(fā)送請(qǐng)求之后,會(huì)自動(dòng)被In-memory
Web API攔截,在in-memory數(shù)據(jù)存儲(chǔ)器中管理,并返回模擬的數(shù)據(jù)響應(yīng)。
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里導(dǎo)入:
import { HttpClientInMemoryWebApiModule } from 'angular-in-memory-web-api'; import { InMemoryDataService } from './in-memory-data.service';并添加到NgModule的imports區(qū)域內(nèi):
目前還缺少一個(gè)in-memory-data.service,
使用下列的命令行生成:
ng generate service InMemoryData
inMemoryData service的實(shí)現(xiàn)代碼:
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里,通過(guò)構(gòu)造函數(shù)參數(shù)注入http client:
定義一個(gè)私有屬性:
private heroesUrl = ‘a(chǎn)pi/heroes’; // URL to web api
這個(gè)property的值符合格式:/
其中base是請(qǐng)求的資源,而collectionName是in-memory-data-service.ts中的heroes對(duì)象:
在hero service里,將之前of返回的fake hero數(shù)據(jù)替換成使用http請(qǐng)求:
運(yùn)行時(shí)的調(diào)試
入口是observable的subscribe方法:
http請(qǐng)求在http.js的intercept方法里被攔截了:
In-Memory Web API的服務(wù)方式是lazy load,即第一次需要服務(wù)之前才會(huì)初始化內(nèi)存數(shù)據(jù)庫(kù):
此處調(diào)用開(kāi)發(fā)人員在應(yīng)用程序里編寫的createDb方法:
要獲取更多Jerry的原創(chuàng)文章,請(qǐng)關(guān)注公眾號(hào)"汪子熙":
總結(jié)
以上是生活随笔為你收集整理的Angular In-memory Web API使用介绍的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: 偌星starlike星语者怎么招募
- 下一篇: 泰拉瑞亚狂星之怒获如何获取