angular获取服务器返回信息,Angular(14) - 从服务端获取数据 - 官方教程英雄指南之添加模拟服务器 (详细解说)...

本文介绍了如何在Angular应用中安装并配置模拟服务器(Angular In-Memory Web API),详细步骤包括导入模块、创建InMemoryData服务和模拟数据。通过InMemoryDataService,为应用程序提供预定义的数据,以便于本地开发和测试。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1 加入HTTP服务

src/app/app.module.ts (

导入服务

import { HttpClientModule } from [email protected]/common/http‘;

@NgModule({

imports: [

HttpClientModule,

],

})

2 模拟数据服务器

2.1 安装官方模拟服务器

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

2.2

src/app/app.module.ts

import { HttpClientInMemoryWebApiModule } from ‘angular-in-memory-web-api‘;

import { InMemoryDataService } from ‘./in-memory-data.service‘;

HttpClientModule,

// The HttpClientInMemoryWebApiModule module intercepts HTTP requests

// and returns simulated server responses.

// Remove it when a real server is ready to receive requests.

HttpClientInMemoryWebApiModule.forRoot(

InMemoryDataService, { dataEncapsulation: false }

)

3 ### 创建 InMemoryData 组件, 通过服务提供数据

ng generate service InMemoryData

import { Injectable } from [email protected]/core‘;

import { InMemoryDbService } from ‘angular-in-memory-web-api‘;

import { Hero } from ‘./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;

}

}

总结,到此,我们的模拟服务器就安装好了,下节我们讲一下如何在服务中使用HTTP

原文:https://www.cnblogs.com/start2019/p/13534719.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值