内存中的角度web api null body in post

时间:2018-04-16 01:40:35

标签: angular angular-in-memory-web-api

我的角度应用程序中有一个post方法,它有一个空体。内存中的web api一直给出null没有item.id错误,但是如果我传递{}而不是null它就可以了。

我不想更改我在内存中的web api测试的实际调用,所以想知道是否有任何方法使我的内存web api不尝试添加任何内容或转换null至 {}。基本上我的post方法除了ping服务器之外没什么用呢

1 个答案:

答案 0 :(得分:0)

我遇到了和你一样的问题。在使用in-memory-web-api尝试覆盖类似于post的自述说明的parseRequestUrl方法后,我没有取得多大成功;只是在那里分道扬。

相反,我选择使用Angular HttpInterceptor,这似乎是现在回顾的逻辑决定。

创建一个检查空POST主体的HTTP拦截器类。如果找到,请将请求克隆为it should be considered immutable,并将正文设置为空对象{}。如果有POST主体,则继续正常处理请求。然后导入AppModule中的拦截器并包含在模块providers数组中。

创建文件http-post-interceptor.ts

import { Injectable } from '@angular/core';
import {
 HttpEvent,
 HttpInterceptor,
 HttpHandler,
 HttpRequest
} from '@angular/common/http';
import { Observable } from 'rxjs';

@Injectable()
export class HttpPostInterceptor implements HttpInterceptor {
  constructor() {}

  intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    // if request body is falsey
    if (!req.body) {
      // clone immutable request and set empty POST body
      const request = req.clone({ body: {} });
      // continue with our modified POST request
      return next.handle(request);
    }
    // else continue with the unmodified POST
    return next.handle(req);
  }
}

HttpPostInterceptorHTTP_INTERCEPTORS导入app.module.ts

// ...
import { /*...*/ HTTP_INTERCEPTORS } from '@angular/common/http';
import { HttpPostInterceptor } from './http-post-interceptor';
// ...

@NgModule({
  // ...
  providers: [
    { provide: HTTP_INTERCEPTORS, useClass: HttpPostInterceptor, multi: true }
  ],
  // ...
})

这就是它的全部内容。

这解决了我在当地环境中遇到的问题所以我不再收到你问题中提到的错误。

在生产版本中停用

由于in-memory-web-api通常是非生产工具,因此您可能希望在生产版本中将其排除。通过导入environment设置并检查生产属性是true还是false来执行此操作。这可以根据您的需要在拦截器或模块中完成。下面的示例通过AppModule显示此内容。

environment设置导入app.module.ts

// ...
import { environment } from '../environments/environment'; 
// ...

@NgModule({
  // ...
  providers: [
    environment.production ? [] :
      { provide: HTTP_INTERCEPTORS, useClass: HttpPostInterceptor, multi: true }
  ]
  // ...
})

注意:某些导入路径可能会因您的项目结构而异,如果您使用的是Angular 6,特别是来自Observable的{​​{1}}