使用哪一个来构建模拟Web服务来测试ANGLING 4应用程序?

推荐答案

如果你使用的是Angular 4.3,请使用HttpClientModule中的HttpClient类.x及以上:

import { HttpClientModule } from '@angular/common/http';

@NgModule({
 imports: [
   BrowserModule,
   HttpClientModule
 ],
 ...

 class MyService() {
    constructor(http: HttpClient) {...}

它是从@angular/http模块升级到http的版本,有以下改进:

  • 拦截器允许将中间件逻辑插入到管道中
  • 不可变的请求/响应对象
  • 请求上载和响应下载的进度事件

你可以在Insider’s guide into interceptors and HttpClient mechanics in Angular里读到它是如何工作的.

  • 类型化、同步响应主体访问,包括对JSON主体类型的支持
  • JSON是假定的默认值,不再需要显式解析
  • 请求后验证&;基于flush的测试框架

今后,旧的http客户端将被弃用.以下是commit messagethe official docs的链接.

还要注意,旧的http是使用Http类令牌而不是新的HttpClient类令牌注入的:

import { HttpModule } from '@angular/http';

@NgModule({
 imports: [
   BrowserModule,
   HttpModule
 ],
 ...

 class MyService() {
    constructor(http: Http) {...}

此外,新HttpClient在运行时似乎需要tslib,所以如果使用SystemJS,则必须安装npm i tslib并更新system.config.js:

map: {
     ...
    'tslib': 'npm:tslib/tslib.js',

如果您使用SystemJS,则需要添加另一个映射:

'@angular/common/http': 'npm:@angular/common/bundles/common-http.umd.js',

Angular相关问答推荐

单元测试 case 模拟store 中的行为主体

如何在Angular 17中使用Angular—calendum?

NG构建后多余的国旗

具有多重签名的Angular Mocking Service

带迭代的Angular 内容投影

Angular 单位测试表

使用 TAB 键时如何聚焦mat-select组件?

Router.navigate() 在功能拦截器内不起作用

URL 更改但组件未在 Angular 导航中呈现

具有两个订阅方法的 Angular 16 takeUntilDestroyed 运算符

Angular AuthGuard:不推荐使用 CanActivate 和 CanActivateChild.如何更换它们?

在 kubernetes 上创建 Ingress 服务以将 springboot [后端] 连接到前端 [angular]

如何重置表单中的特定字段?

如何在 Angular 2 中使用 protractor ?

如何在 Angular Cli 中生成 .angular-cli.json 文件?

如何在 ngFor angular 2 内部使用 track

Angular将 Select 值转换为 int

如何在 Angular cli 项目中包含来自 node_modules 的assets

Firestore 从集合中获取文档 ID

Angular2:CoreModule 与 SharedModule