【问题标题】:Angular in memory web api null body in post帖子中的内存Web api空体中的角度
【发布时间】:2018-06-01 17:41:32
【问题描述】:

我的 Angular 应用程序中有一个 post 方法,它的主体为空。内存中的 web api 不断给出 null 没有 item.id 错误,但如果我通过 {} 而不是 null 它工作正常。

我不想更改内存中 web api 测试的实际发布调用,所以想知道是否有任何方法可以让我的内存中 web api 不尝试添加任何内容或将 null 转换为 { }。基本上我的 post 方法除了 ping 服务端并没有什么作用

【问题讨论】:

  • 当然,它会给你的 item.id 错误,你正在访问一个空值的 id 属性。当您通过 {} 并访问其属性 id 时,id 为 null 而不是项目。
  • 是的,我的问题是是否有任何方法可以让内存中的 web api 不尝试访问 id 属性(如果它为空)
  • 尝试发送 undefined 而不是 null。 in-memory-web-api 有未定义的检查,但没有 null
  • 谢谢,但不幸的是 undefined 也出现同样的错误
  • @aks94 你找到解决这个问题的方法了吗?

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


【解决方案1】:

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

相反,我选择使用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,尤其是从 rxjs 导入的 Observable

【讨论】:

    猜你喜欢
    • 2016-03-31
    • 2015-06-17
    • 2020-04-11
    • 1970-01-01
    • 1970-01-01
    • 2020-10-13
    • 2017-05-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多